Por admin | Para la categoría de jsf (java server faces) | noticia del 25-07-2010
Ejemplo de conexión de una base de datos con el framework java server faces
La conexión se realiza mediante un fichero de configuración datasource, siendo más flexible para el desarrollo de una aplicación, ya que si en las clases de modelos se tienen que hacer en todas y cada una de ellas una configuración de los drivers específica de la aplicación, se pierde flexibilidad a la hora de extender y ampliar.
incorporación en el archivo web.xml del Conector
1 2 3 4 5 6 | <resource-ref> <description>DB Connection</description> <res-ref-name>jdbc/datasource</res-ref-name> <res-type>javax.sql.DataSource</res-type> <res-auth>Container</res-auth> </resource-ref> |
Configuración del fichero context.xml , igual que los ejemplos explicados de j2ee
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | <?xml version="1.0" encoding="UTF-8"?> <Context path="/DBTest" docBase="DBTest" debug="5" reloadable="true" crossContext="true"> <!-- maxActive: Maximum number of dB connections in pool. Make sure you configure your mysqld max_connections large enough to handle all of your db connections. Set to -1 for no limit. --> <!-- maxIdle: Maximum number of idle dB connections to retain in pool. Set to -1 for no limit. See also the DBCP documentation on this and the minEvictableIdleTimeMillis configuration parameter. --> <!-- maxWait: Maximum time to wait for a dB connection to become available in ms, in this example 10 seconds. An Exception is thrown if this timeout is exceeded. Set to -1 to wait indefinitely. --> <!-- username and password: MySQL dB username and password for dB connections --> <!-- driverClassName: Class name for the old mm.mysql JDBC driver is org.gjt.mm.mysql.Driver - we recommend using Connector/J though. Class name for the official MySQL Connector/J driver is com.mysql.jdbc.Driver. --> <!-- url: The JDBC connection url for connecting to your MySQL dB. --> <Resource name="jdbc/datasource" auth="Container" type="javax.sql.DataSource" maxActive="100" maxIdle="30" maxWait="10000" username="root" password="root" driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/libros_jdbc"/> </Context> |
una vez creado los elementos necesarios para la conexión ya explicados en otros post creamos los formularios de recogida de datos y los bean asociados a los formularios
Bean libro.java asociado al formulariojdbc.jsp, creamos las propiedades de la tabla libros con los tres campos y sus correspondientes getters y setters
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | package beans; public class Libros { private String titulo; private String autor; private String tematica; public String getTitulo() { return titulo; } public void setTitulo(String titulo) { this.titulo = titulo; } public String getAutor() { return autor; } public void setAutor(String autor) { this.autor = autor; } public String getTematica() { return tematica; } public void setTematica(String tematica) { this.tematica = tematica; } } |
Este bean es el encargado de recoger los datos del formulario, el formulario de jsf cuando detecta una etiqueta que hace referencia a un bean mediante el lenguaje de expresión intenta conectarse siendo necesario dar de alta en el fichero faces-config.xml el bean libros
1 2 3 4 5 | <managed-bean> <managed-bean-name>libroBean</managed-bean-name> <managed-bean-class>beans.Libros</managed-bean-class> <managed-bean-scope>request</managed-bean-scope> </managed-bean> |
nombre del bean para ser usado, path y ámbito
Código del formulariojdbc.jsf encargado de recoger los datos correspondientes al libro
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="f" uri="http://java.sun.com/jsf/core"%> <%@ taglib prefix="h" uri="http://java.sun.com/jsf/html"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <f:view> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <link rel="stylesheet" type="text/css" href="../css/estilo.css" /> <title>formulario jsf jdbc</title> </head> <body> <h2><h:outputText value="formulario libros"/></h2> <div id="contenedor"> <h:form> <div class="campo"> <h:outputText value="introduce el título"/> <br/> <h:inputText value="#{libroBean.titulo}"/> </div> <div class="campo"> <h:outputText value="introduce el autor"/> <br/> <h:inputText value="#{libroBean.autor}"/> </div> <div class="campo"> <h:outputText value="introduce la temática"/> <br/> <h:inputText value="#{libroBean.tematica}"/> </div> <h:commandButton action="almacenaraction" actionListener="#{almacenarlibro.insertarLibro}" value="enviar" styleClass="boton"/> </h:form> <div id="pie"> <p>www.railsymas.com</p> </div> </div> </body> </f:view> </html> |
Bean encargado de la tramitación de los datos a la base de datos
1 2 3 4 5 | <managed-bean> <managed-bean-name>almacenarlibro</managed-bean-name> <managed-bean-class>conexion.OperacionesConexion</managed-bean-class> <managed-bean-scope>request</managed-bean-scope> </managed-bean> |
Imagen correspondiente al formulariojdbc.jsp

Código de la página listadojsf
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 | <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="f" uri="http://java.sun.com/jsf/core"%> <%@ taglib prefix="h" uri="http://java.sun.com/jsf/html"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <f:view> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Listado libros</title> <link rel="stylesheet" href="../css/estilo.css" type="text/css" /> </head> <body> <div id="contenedor"> <h2>Listado libros jdbc jsf</h2> <div id="tabla"> <h:dataTable styleClass="tabla" value="#{almacenarlibro.listalibros}" var="libro" headerClass="cabeceratabla" columnClasses="impar,par,impar" cellspacing="2" footerClass="pietabla"> <h:column> <f:facet name="header"> <h:outputText>Título</h:outputText> </f:facet> <h:outputText value="#{libro.titulo}"/> </h:column> <h:column> <f:facet name="header"> <h:outputText>Autor</h:outputText> </f:facet> <h:outputText value="#{libro.autor}"/> </h:column> <h:column> <f:facet name="header"> <h:outputText>Temática</h:outputText> </f:facet> <h:outputText value="#{libro.tematica}"/> </h:column> <f:facet name="footer" > <h:outputText> listado tabla</h:outputText> </f:facet> </h:dataTable> </div> <div id="pie"> <p>www.railsymas.com</p> </div> </div> </body> </f:view> </html> |
