JavaDabbaDoo.org -Tu comunidad Java parlante Implementar MVC - Struts 1.2
Inicio | Cursos infosintesis.net liberados | Java EE | Registrar a un usuario en un sitio Web con Struts 1.2
Registrar a un usuario en un sitio Web con Struts 1.2
Paso 4: Operativa

Vista - RegistroActionForm, registroForm.jsp - No validar un formulario cuando se realiza la primera petición

Cuando una aplicación Web que utiliza el Framework Struts recibe la petición http://localhost:8080/proregusuariostruts/registro.do, el mapeo del Servlet en el descriptor de despliegue web.xml de la aplicación o contexto indica que la Clase que se tiene que ejecutar es ActionServlet porque en este caso registro.do sigue el patrón de url <url-pattern>*.do</url-pattern>.

Entonces ActionServlet crea una instancia de la Clase org.apache.struts.action.RequestProcessor que se responsabiliza de procesar la petición realizada por el usuario.

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"                        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"                        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee                        http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
 <servlet>
  <servlet-name>
action</servlet-name>
  <servlet-class>
org.apache.struts.action.ActionServlet</servlet-class>
  <init-param>
   <param-name>config</param-name>
   <param-value>/WEB-INF/struts-config.xml</param-value>
  </init-param>
  <init-param>
   <param-name>debug</param-name>
   <param-value>2</param-value>
  </init-param>
  <init-param>
   <param-name>detail</param-name>
   <param-value>2</param-value>
  </init-param>
  <load-on-startup>2</load-on-startup>
 </servlet>
 <servlet-mapping>
  <servlet-name>
action</servlet-name>
  <url-pattern>
*.do</url-pattern>
 </servlet-mapping>

 <session-config>
  <session-timeout>
   30
  </session-timeout>
 </session-config>
 <welcome-file-list>
  <welcome-file>index.jsp</welcome-file>
 </welcome-file-list>
</web-app>

RequestProcessor entonces hecha un vistazo al fichero struts-config.xml para ver si la acción con el path /registro tiene asociada un ActionForm. En nuestro ejemplo la subclase de ActionForm asociada a esta acción es paqactionforms.RegistroActionForm.

<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE struts-config PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 1.2//EN"
"http://jakarta.apache.org/struts/dtds/struts-config_1_2.dtd">

<struts-config>
 <form-beans>
  <form-bean name
="RegistroActionForm" type="paqactionforms.RegistroActionForm"/>
 </form-beans>


 <global-exceptions>

 </global-exceptions>

 <global-forwards>
  <forward name="welcome" path="/Welcome.do"/>
 </global-forwards>

 <action-mappings>
  <action input
="/registroForm.jsp" name="RegistroActionForm" path="/registro" 
   
scope="session" type="paqactions.RegistroAction"/>
  <action path="/Welcome" forward="/welcomeStruts.jsp"/>
 </action-mappings>

 <controller processorClass="org.apache.struts.tiles.TilesRequestProcessor"/>

 <message-resources parameter="literales/ApplicationResource"/>

 <plug-in className="org.apache.struts.tiles.TilesPlugin" >
  <set-property property="definitions-config" value="/WEB-INF/tiles-defs.xml" />
  <set-property property="moduleAware" value="true" />
 </plug-in>

 <!-- ================= Validator plugin ========================= -->
 <plug-in className="org.apache.struts.validator.ValidatorPlugIn">
  <set-property
   property="pathnames"
   value="/WEB-INF/validator-rules.xml,/WEB-INF/validation.xml"/>
 </plug-in>

</struts-config>

Entonces RequestProcessor determina el scope o ámbito de la Clase RegistroActionForm y seguidamente RequestProcessor comprueba si ya existe una instancia de RegistroActionForm.

El método RequestProcessor.processPopulate() realiza tres acciones en el siguiente orden

Teniendo en cuenta el flujo de ejecución de una aplicación Struts, tenemos que evitar que el método validate() realice la validación de los datos la primera vez que se muestra el formulario para que el formulario en cuestión no esté repleto de mensajes de error.

Para ello vamos a ampliar la Clase RegistroActionForm

package paqactionforms;

import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;

public class RegistroActionForm extends org.apache.struts.action.ActionForm {

 
private boolean submitRealizado = false;

 private String nombre;
 private String apellido;

 public RegistroActionForm() {
  super();
 }

 public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
 
 System.out.println("---- Entrada en validate()");
  ActionErrors errors = new ActionErrors();
  if (submitRealizado) {
   if (getNombre() == null || getNombre().length() < 1) {
    errors.add("nombre", new ActionMessage("error.nombre.requerido"));
   }

   if (getApellido() == null || getApellido().length() < 1) {
    errors.add("apellido", new ActionMessage("error.apellido.requerido"));
   }
  } else {
   errors.add("noSubmitRealizado", new ActionMessage(""));
  }

  return errors;
 }

 public String getNombre() {
  return nombre;
 }

 public void setNombre(String nombre) {
  this.nombre = nombre;
 }

 public String getApellido() {
  return apellido;
 }

 public void setApellido(String apellido) {
  this.apellido = apellido;
 }

 public void setSubmitRealizado(boolean submitRealizado) {
  this.submitRealizado = submitRealizado;
 }

}

Y también le vamos a añadir un elemento <html:hidden> al formulario de la página JSP registroForm.jsp.

<%@page contentType="text/html" pageEncoding="UTF-8"%>

<%@ taglib uri="http://jakarta.apache.org/struts/tags-html" prefix="html" %>
<%@ taglib uri="http://jakarta.apache.org/struts/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">
 <title>Formulario Registro usuario Struts 1.2</title>
 <link rel="stylesheet" href="/proregusuariostruts/css2/estilos.css" type="text/css">
</head>
<body>
 <html:form action="registro">
  <html:hidden property="submitRealizado" value="true" />
  <div style="left: 210px; top: 10px; font-size: 24px;
       font-weight: bold; position: absolute">
   <bean:message key="literal.registroUsurario" />
  </div>
  <div style="left: 250px; top: 40px; font-size: 10px; position: absolute">
   *<bean:message key="literal.camposRequeridos" />
  </div>

  <div style="left: 28px; top: 80px; position: absolute">
   <bean:message key="literal.nombre" />*
  </div>
  <div style="left: 28px; top: 100px; position: absolute">
   <html:text property="nombre" size="40" />
  </div>
  <div style="left: 28px; top: 123px; position: absolute">
   <html:errors property="nombre" />
  </div>

  <div style="left: 320px; top: 80px; position: absolute">
   <bean:message key="literal.apellido" />*
  </div>
  <div style="left: 320px; top: 100px; position: absolute">
   <html:text property="apellido" size="40" />
  </div>
  <div style="left: 320px; top: 123px; position: absolute">
   <html:errors property="apellido" />
  </div>
 </html:form>
</body>
</html>

Página anterior
Ignasi Pérez Valls
Infosintesis Solutions Group


Junio 2009
JavaDabbaDoo.org
Tu comunidad Java parlante. Cursos abiertos, tutoriales y mucho mucho más ...