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 2: Operativa

Vista - RegistroActionForm - Crear el esqueleto de un ActionForm

Las subclases del JavaBean ActionForm representan a datos compartidos entre la vista y las subclases de los objetos de tipo Action.

Las subclases de ActionForm se utilizan para

Las subclases de ActionForm no deberían tener código relacionado con la lógica de negocio.

Ahora vamos a crear una subclase de ActionForm llamada RegistroActionForm. Para ello en la ventana properties vamos a hacer clic con el botón derecho sobre nuestro proyecto de ejemplo llamado proregusuariostruts y seleccionamos Other...

Entonces elegimos Struts | Struts ActionFormBean

NetBeans 6 - Crear una subclase de ActionForm - Struts | Struts ActionForm Bean

En el cuadro de diálogo New Struts ActionForm Bean escribimos los siguientes datos

NetBeans 6 - Crear una subclase de ActionForm - Name and Location | Class Name: RegistroActionForm | Superclass: org.apache.struts.action.ActionForm | Configuration File: /WEB-INF/struts-config.xml

Para salir de este asistente hacemos clic sobre el botón Finish.

Como podemos observar, en el fichero struts-config.xml el asistente de NetBeans ha añadido el elemento <form-bean>

<?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 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>

y también ha creado el esqueleto de la Clase RegistroActionForm que hereda de la Clase ActionForm

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 String name;
 private int number;

 public String getName() {
  return name;
 }

 public void setName(String string) {
  name = string;
 }

 public int getNumber() {
  return number;
 }

 public void setNumber(int i) {
  number = i;
 }

 public RegistroActionForm() {
  super();
 }

 public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
  ActionErrors errors = new ActionErrors();
  if (getName() == null || getName().length() < 1) {
   errors.add("name", new ActionMessage("error.name.required"));
   // TODO: add 'error.name.required' key to your resources
  }
  return errors;
 }
}

Ahora vamos a realizar los primeros cambios para que los nombres de los componentes del formulario que crearemos más adelante coincidan con las varibles de instancia de la subclase de ActionForm.

También vamos a modificar el método validate(...) para que compruebe que los campos de texto nombre y apellido son correctos.

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 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 (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"));
  }

  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;
 }
}

En el fichero literales/ApplicationResource.properties añadimos los dos primeros mensajes de error

literal.registroUsurario=Registro de usuario
literal.camposRequeridos=Campos requeridos

error.nombre.requerido=Nombre obligatorio
error.apellido.requerido=Apellido obligatorio

errors.header=<UL>
errors.prefix=<LI>
errors.suffix=</LI>
errors.footer=</UL>
errors.invalid={0} is invalid.
errors.maxlength={0} can not be greater than {1} characters.
errors.minlength={0} can not be less than {1} characters.
errors.range={0} is not in the range {1} through {2}.
errors.required={0} is required.
errors.byte={0} must be an byte.
errors.date={0} is not a date.
errors.double={0} must be an double.
errors.float={0} must be an float.
errors.integer={0} must be an integer.
errors.long={0} must be an long.
errors.short={0} must be an short.
errors.creditcard={0} is not a valid credit card number.
errors.email={0} is an invalid e-mail address.
errors.cancel=Operation cancelled.
errors.detail={0}
errors.general=The process did not complete. Details should follow.
errors.token=Request could not be completed. Operation is not in sequence.
welcome.title=Struts Application
welcome.heading=Struts Applications in Netbeans!
welcome.message=It's easy to create Struts applications with NetBeans.

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 ...