07 noviembre, 2006

Model View Controller - Struts

...
Resumen


Struts nos permite mantener bien separas las vistas (páginas JSP) del modelo (Facade y todo lo que está por detrás). Pero también provee herramientas para facilitar la programación de la funcionalidad de las páginas web. Por ejemplo los formularios.

Es decir que para que una página JSP contenga un formulario tendremos que realizar una serie de pasos. En este nuevo ejemplo analizaremos una página para registrar nuevos usuarios. Se llamará nuevoUsuario.jsp.

Entonces los pasos serán los siguientes:

1 - Crear una entrada dentro del TAG action-mapping en el archivo struts-config.xml con los siguientes parámetros:

   1:
2: <action
3: path="/nuevoUsuario"
4: type="test.struts.action.NuevoUsuarioAction"
5: input="/nuevoUsuario.jsp"
6: name="nuevoUsuarioForm">
7: </action>
8:

2 - Definir una entrada dentro del TAG form-beans también en el archivo struts-config.xml definiendo el form para nuestra página.

   1:
2:<form-beans>
3: <form-bean
4: name="nuevoUsuarioForm"
5: type="test.struts.form.NuevoUsuarioForm"/>
6:</form-beans>
7:

3 - Crear la clase NuevoUsuarioAction.java que debe extender de Action y sobreescribir el método execute.

4 - Crear la clase NuevoUsuarioForm.java que debe extender de ActionForm y sobreescribir el método validate. Además debe tener un atributo por cada campo del formulario HTML.

Veamos la página y luego el código.



nuevoUsuario.jsp
   1:
2:<%@ taglib uri="/WEB-INF/struts-html.tld"
3: prefix="html"%>
4:
5:<html:html>
6:<body>
7: <html:form action="/nuevoUsuario.do">
8: <table>
9: <tr><td>Nombre de Usuario</td>
10: <td>
11: <html:text property="usuario" />
12: <font color="red">
13: <html:errors property="usuario" />
14: </font>
15: </td>
16: </tr>
17: <tr><td>Clave</td>
18: <td>
19: <html:password property="clave1" />
20: <font color="red">
21: <html:errors property="clave1" />
22: </font>
23: </td>
24: </tr>
25: <tr><td>Reingrese la Clave</td>
26: <td>
27: <html:password property="clave2" />
28: <font color="red">
29: <html:errors property="clave2" />
30: </font>
31: </td>
32: </tr>
33: <tr><td>Dirección de Email</td>
34: <td>
35: <html:text property="email" />
36: <font color="red">
37: <html:errors property="email" />
38: </font>
39: </td>
40: </tr>
41: <tr>
42: <td colspan="2">
43: <html:submit value="Enviar"/>
44: <html:reset/></td>
45: </td>
46: </table>
47: </html:form>
48:</body>
49:</html:html>
50:

NuevoUsuarioForm.java
   1:
2:
package test.struts.form;
3:import javax.servlet.http.HttpServletRequest;
4:import org.apache.struts.action.ActionErrors;
5:import org.apache.struts.action.ActionForm;
6:import org.apache.struts.action.ActionMapping;
7:import org.apache.struts.action.ActionMessage;
8:
9:public class NuevoUsuarioForm extends ActionForm
10:{
11: private String usuario;
12: private String clave1;
13: private String clave2;
14: private String email;
15:
16: public ActionErrors validate(
17: ActionMapping arg0
18: , HttpServletRequest arg1)
19: {
20: ActionErrors errores=new ActionErrors();
21:
22: // usuario no puede estar vacio
23: if( usuario.trim().length()<=0 )
24: {
25: errores.add(
26: "usuario"
27: ,new ActionMessage("nuevoUsr.usr.vacio"));
28: }
29:
30: // Por ejemplo, 5 caracteres como minimo
31: if( clave1.trim().length()<5 )
32: {
33: errores.add(
34: "clave1"
35: ,new ActionMessage(
36: "nuevoUsr.clave.corta"));
37: }
38:
39: // la clave 2 debe ser igual a la primera
40: if( !clave2.equals(clave1) )
41: {
42: errores.add("clave2"
43: ,new ActionMessage(
44: "nuevoUsr.clave.noCoincide"));
45: }
46:
47: // el mail debe tener al menos una "@"
48: if( email.indexOf('@')<0 )
49: {
50: errores.add("email"
51: ,new ActionMessage(
52: "nuevoUsr.mail.malFormato"));
53: }
54:
55: return errores;
56: }
57:
58: public String getClave1()
59: {
60: return clave1;
61: }
62:
63: public void setClave1(String clave1)
64: {
65: this.clave1 = clave1;
66: }
67:
68: public String getClave2()
69: {
70: return clave2;
71: }
72:
73: public void setClave2(String clave2)
74: {
75: this.clave2 = clave2;
76: }
77:
78: public String getEmail()
79: {
80: return email;
81: }
82:
83: public void setEmail(String email)
84: {
85: this.email = email;
86: }
87:
88: public String getUsuario()
89: {
90: return usuario;
91: }
92:
93: public void setUsuario(String usuario)
94: {
95: this.usuario = usuario;
96: }
97:}
98:

struts-config.xml
   1:
2:<?xml version="1.0" encoding="UTF-8"?>
3:<!DOCTYPE struts-config PUBLIC "-//Apache Software
4:Foundation//DTD Struts Configuration 1.2//EN"
5:"http://struts.apache.org/dtds/struts-config_1_2.dtd">
6:
7:<struts-config>
8: <data-sources />
9: <form-beans>
10: <form-bean
11: name="nuevoUsuarioForm"
12: type="test.struts.form.NuevoUsuarioForm" />
13: </form-beans>
14: <global-exceptions />
15: <global-forwards />
16: <action-mappings>
17: <action
18: path="/nuevoUsuario"
19: type="test.struts.action.NuevoUsuarioAction"
20: input="/nuevoUsuario.jsp"
21: name="nuevoUsuarioForm">
22: </action>
23:
24: </action-mappings>
25: <message-resources
26: parameter="test.struts.ApplicationResources" />
27:</struts-config>
28:

NuevoUsuarioAction.java
   1:
2:package test.struts.action;
3:
4:import javax.servlet.http.HttpServletRequest;
5:import javax.servlet.http.HttpServletResponse;
6:
7:import org.apache.struts.action.Action;
8:import org.apache.struts.action.ActionForm;
9:import org.apache.struts.action.ActionForward;
10:import org.apache.struts.action.ActionMapping;
11:
12:public class NuevoUsuarioAction extends Action
13:{
14: public ActionForward execute(
15: ActionMapping mapping
16: , ActionForm form
17: , HttpServletRequest request
18: , HttpServletResponse response)
19: throws Exception
20: {
21: return mapping.findForward("ok");
22: }
23:}
24: