Datasource struts 1.3.x proyecto web eclipse

0

Por admin | Para la categoría de struts | noticia del 11-01-2010

ejerciciodatasource

integración del enlace en la página web de ejercicios

1
2
3
 <div class="enlace">
   <html:link action="/datasource"> 7) datasource </html:link>
   </div>

configuración de la acción datasource.do en el struts-config.xml

1
2
3
4
 <action         
         path="/datasource"
         forward="/pages/formulariodatasource.jsp" 
         />

Configuración del bean en el fichero struts-config.xml, es la configuración del bean dinámico con las propiedades de la tabla de la base de datos libros campo titulo, temática y autor vistos en jdbc j2ee

1
2
3
4
5
<form-bean name="beandatasource" type="org.apache.struts.validator.DynaValidatorForm">    
    <form-property name="titulo" type="java.lang.String"/>
    <form-property name="tematica" type="java.lang.String"/>
    <form-property name="autor" type="java.lang.String"/>      
    </form-bean>

Configuración del fichero de propiedades

1
2
3
4
5
6
7
8
9
#datasource
formulariodatasource.crear = enviar
formulariodatasource.cancelar = cancelar
formulariodatasource.titulo = formulario datasource
formulariodatasource.titulolibro = titulo
formulariodatasource.tematica = tematica
formulariodatasource.autor = autor
formulariodatasource.resultado = listado de libros
datasourceresultado.titulo = listado de datos

Si intentamos crear el datasource al igual que hacíamos con la versión 1.2 nos da error, en el archivo de configuración de struts

error2

La dtd de struts 1.3 soporta un conjunto de etiquetas en el orden que se indica en la siguiente imagen.

error1

El tag no viene soportado para esta dtd

Explicaciones del proyecto struts en el wiki datasource

Removed the and elements

creamos un package nuevo para albergar al bean libro, package vo, se llama así por el patrón value object

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
package vo;
 
public class Libro {
 
	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;
	}
 
}

Clase Conexion dentro del package conexiones

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
package conexiones;
 
import java.sql.Connection;
import java.sql.SQLException;
 
import javax.sql.DataSource;
import javax.naming.InitialContext;
import javax.naming.NamingException;
 
 
public class Conexion {
 
	private Connection conexion = null;
 
	public Conexion ()
	{  
 
 
	}
 
	public Connection establecerConexion()
	{
 
		try
		{
 
			InitialContext contexto = new InitialContext();
			DataSource ds = (DataSource) contexto.lookup("java:comp/env/jdbc/datasource");
			this.conexion = ds.getConnection();		
 
 
		}
		catch (NamingException e)
		{
			System.out.println(e.getMessage());
		}
 
		catch (SQLException e )
		{
			System.out.println(e.getMessage());
		}
 
		return this.conexion;
 
	}
 
}

Configuración del fichero web.xml

1
2
3
4
5
6
7
<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>
      <res-sharing-scope>shareable</res-sharing-scope>
  </resource-ref>

fichero context.xml

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>

Configuración de la acción formulariodatasource.do

1
2
3
4
5
6
7
8
9
10
11
12
13
 <action 
         path="/formulariodatasource"
         type="acciones.ConexionDatasource"
         scope="request"
         validate="true"
         name="beandatasource"
         input="/pages/formulariodatasource.jsp">
 
         <set-property property="cancellable" value="true" /> 
 
         <forward name="cancelada" path="/pages/cancelada2.jsp"></forward>
         <forward name="mostrardatos" path="/pages/mostrarlistado.jsp"> </forward>
   </action>
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
package acciones;
 
 
import conexiones.Conexion;
import vo.Libro;
 
import java.io.PrintWriter;
import java.sql.SQLException;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.validator.DynaValidatorForm;
import java.sql.Statement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.util.ArrayList;
import javax.servlet.http.HttpSession;
 
 
 
public class ConexionDatasource extends Action {
 
	private Connection conexionr = null;
	private ActionForward envio  = null;
	private Conexion conexion = null;
	private Statement sentenciaSql;
	private ResultSet resultado = null;
	private Libro libro;
	private ArrayList<Libro> listalibros; 
	private HttpSession session = null;
 
	public ActionForward execute (ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception 
	{
 
		DynaValidatorForm formulario = (DynaValidatorForm)form;
		conexion = new Conexion();
		response.setContentType("Text/html");
 
		PrintWriter salida = response.getWriter();
 
		if (this.isCancelled(request))
		{
			envio = mapping.findForward("cancelada");
		}
 
		else
		{
 
 
		try
		{
 
		   conexionr = conexion.establecerConexion();
 
		   sentenciaSql = conexionr.createStatement();	   
 
		   //ejecutamos la sentencia de selección de los campos menos el id
 
		   System.out.print(formulario.get("titulo"));
		   System.out.print(formulario.get("autor"));
		   System.out.print(formulario.get("tematica"));		   
 
		   sentenciaSql.executeUpdate(" INSERT INTO libros VALUES ("+0+",'"+formulario.get("titulo")+"','"+formulario.get("autor")+"','"+formulario.get("tematica")+"');");
 
		   //recuperamos los datos de la base de datos
 
		   resultado = sentenciaSql.executeQuery("SELECT * from libros;");
 
		   if ( resultado != null)
		   {
			   //creamos el array de libros
			   listalibros = new  ArrayList<Libro>(); 
 
			   while (resultado.next())
			   {   
				   libro = new Libro(); 
				   libro.setTitulo(resultado.getString("titulo"));
				   libro.setAutor(resultado.getString("autor"));
				   libro.setTematica(resultado.getString("tematica"));
 
				   listalibros.add(libro);
			   }
 
			   //cerramos la conexion
			   conexionr.close();
 
			   //establecemos el parámetro por peticion
			   session = request.getSession(true);
			   session.setAttribute("listadolibros", listalibros);  
 
 
			   envio = mapping.findForward("mostrardatos");
 
		   }
 
		}
 
		catch( 	SQLException e )
		{
			salida.println("Excepcion Sql : "+ e.getMessage());
		}
 
		}
 
 
		return envio;
	}	
 
}

formulariodatasource.jsp

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
<%@ page language="java" contentType="text/html; charset=UTF-8"  pageEncoding="UTF-8"%>
<%@taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %>
<%@taglib uri="http://struts.apache.org/tags-html" prefix="html" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html:html>
<head>
<html:base/>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="../css/estilo.css" />
<title><bean:message key="formulariodatasource.titulo"/></title>
</head>
<body>
<div id="contenedor">
<h2><bean:message key="formulariodatasource.titulo"/></h2>
 
<div id="errores">
  <html:errors/> 
</div>
 <div id="imagen">
  <html:img srcKey="dinamico.registro.imagen" titleKey="dinamico.registro.imagen.alt"/>
  </div>
 
<div id="contenido">
<html:form action="formulariodatasource" focus="nombre" styleId="formulario" method="post">
 <div class="campo"> 
  <bean:message key="formulariodatasource.titulolibro"/>
  <html:text property="titulo"/>
  </div> 
  <div class="campo">
  <bean:message key="formulariodatasource.autor"/>
  <html:text property="autor"/>
  </div>
 
  <div class="campo">
  <bean:message key="formulariodatasource.tematica" />
  <html:text property="tematica"/>
  </div>
 
  <html:submit styleClass="boton"> <bean:message key="formulariodatasource.crear"/> </html:submit>
  <html:cancel styleClass="boton"> <bean:message key="formulariodatasource.cancelar"/> </html:cancel>  
  <html:reset  styleClass="boton"> borrar</html:reset>
</html:form>
</div>
<div id="pie">
    <p> www.railsymas.com </p>
</div>
</div>
</body>
</html:html>

Imagen correspondiente

formulariodatasource

mostrarlistado.jsp

Las etiquetas logic nos permiten iterar sobre los resultados obtenidos, logic:empty nos permite saber si el valor de la variable referenciada por name está vacío, en éste caso se utiliza para mostrar el mensaje correspondiente. Para comprobar que no está vacío se utiliza logic:notEmpty, para luego iterar por los resultado con logic:iterate

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
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@taglib uri="http://struts.apache.org/tags-html" prefix="html" %>
<%@taglib uri="http://struts.apache.org/tags-logic" prefix="logic"%>
<%@taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<html:base/>
<title><bean:message key="datasourceresultado.titulo"/></title>
<link rel="stylesheet" href="../css/estilo.css" type="text/css"/>
 
</head>
<body>
<div id="contenedor">   
  <div id="tabla">
  <logic:empty name="listadolibros">
    <p> La base de datos de libros esta vac&iacute;a </p>
  </logic:empty>
 
  <logic:notEmpty name="listadolibros">
  <h2><bean:message key="formulariodatasource.resultado"/></h2>
  <table title="tabla de datos libros">
  <tr><th> titulo </th> <th> autor </th> <th> tematica </th></tr>
 
  <logic:iterate name="listadolibros" id="libro">
  <tr>
    <td class="par">
     <bean:write name="libro" property="titulo"/>
    </td>
    <td class="impar"> 
     <bean:write name="libro" property="autor"/>
    </td>
    <td class="par">
     <bean:write name="libro" property="tematica"/>
    </td>
  </tr>  
  </logic:iterate>
  </table>
  </logic:notEmpty>
  </div>  
 
  <div id="pie">
    <p> www.railsymas.com </p>
  </div>  
  </div>
</body>
</html>

Imagen correspondiente

listado

Comentarios cerrados automáticamente al pasar más de un año