Ejemplo StrutsEsta página recoge uno de los ejemplos de uso de las rutinas ISValidator. Puede así mismo ver los ejemplos que se incluyen en el paquete para descargar. Supongamos que queremos realizar una aplicacion web que funcione con la estructura Struts para mandar emails y registrarlos en una base de datos. A la accion correspondiente se le deben pasar cuatro parámetros:
Si alguna de estas restricciones no se cumpliese se deberá volver a pedir los datos mostrando un mensaje indicantivo de todas las condiciones incumplidas. CódigoVamos a ver este ejemplo que hemos puesto en código Java utilizando ISValidator.
package com.inigoserrano.isvalidator.examples.struts;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import com.inigoserrano.isvalidator.check.DateCheck;
import com.inigoserrano.isvalidator.check.EmailCheck;
import com.inigoserrano.isvalidator.check.RegularExpresionCheck;
import com.inigoserrano.isvalidator.data.SimpleData;
import com.inigoserrano.isvalidator.dataGroup.SimpleDataGroup;
import com.inigoserrano.isvalidator.errorDo.StrutsErrorDo;
import com.inigoserrano.isvalidator.errorDo.StrutsErrorDoGroup;
/**
* This is the ActionForm to capture and validate the parameters
*
* @author Iñigo Serrano
*/
public class ExampleForm extends ActionForm {
/**
* The email
*/
private String email = null;
/**
* The Subject
*/
private String subject = null;
/**
* The Date
*/
private String date = null;
/**
* The Body
*/
private String body = null;
/**
* Constructor for ExampleForm.
*/
public ExampleForm() {
super();
}
/**
* @see org.apache.struts.action.ActionForm#validate
* (ActionMapping, HttpServletRequest)
*/
public ActionErrors validate(
ActionMapping mapping,
HttpServletRequest request) {
try {
//The dataGroup
SimpleDataGroup inputParameters = new SimpleDataGroup();
//For the email
SimpleData theEmail = new SimpleData(this.email, "email");
theEmail.addCheck(new EmailCheck());
theEmail.addCheck(new RegularExpresionCheck(".{1,100}"));
//For the subject
SimpleData theSubject = new SimpleData(this.subject, "subject");
theSubject.addCheck(new RegularExpresionCheck(".{1,255}"));
//For the Date
SimpleData theDate = new SimpleData(this.date, "date");
theDate.addCheck(new DateCheck());
//For the Body
SimpleData theBody = new SimpleData(this.body, "body");
theBody.addCheck(new RegularExpresionCheck(".{1,1000}"));
//we must add the Datas to the DataGroupit.
inputParameters.addData(theEmail);
inputParameters.addData(theSubject);
inputParameters.addData(theDate);
inputParameters.addData(theBody);
//here we are using the dataGroup to check the data
if (inputParameters.check()) {
//All ok return null
return null;
} else {
//There are errors, so using the errorDo and errorDoGroup
//we have the ActionErrors properly configurated
inputParameters.setErrorDo(
new StrutsErrorDo(),
new StrutsErrorDoGroup());
//and return it
return ((StrutsErrorDoGroup) inputParameters.getErrorDoGroup())
.getActionErrors();
}
} catch (Exception e) {
ActionError actionError = new ActionError("internalError");
ActionErrors actionErrors = new ActionErrors();
actionErrors.add(ActionErrors.GLOBAL_ERROR, actionError);
return actionErrors;
}
}
/**
* Returns the body.
* @return String
*/
public String getBody() {
return body;
}
/**
* Returns the date.
* @return String
*/
public String getDate() {
return date;
}
/**
* Returns the email.
* @return String
*/
public String getEmail() {
return email;
}
/**
* Returns the subject.
* @return String
*/
public String getSubject() {
return subject;
}
/**
* Sets the body.
* @param body The body to set
*/
public void setBody(String body) {
this.body = body;
}
/**
* Sets the date.
* @param date The date to set
*/
public void setDate(String date) {
this.date = date;
}
/**
* Sets the email.
* @param email The email to set
*/
public void setEmail(String email) {
this.email = email;
}
/**
* Sets the subject.
* @param subject The subject to set
*/
public void setSubject(String subject) {
this.subject = subject;
}
}
DescripcionVamos a describir paso a paso el codigo. Como se podrá comprobar este es muy sistemático y similar al utilizado en el ejemplo de la línea de comandos Lo primero que se crea es el DataGroup que contendrá los Data. En este caso se utiliza el SimpleDataGroup, que sirve para recoger y modelar datos genéricos, en este caso al ser el ActionForm un bean nos es válido. En otras situaciones se podrían utilizar otros DataGroup.
//The dataGroup
SimpleDataGroup inputParameters = new SimpleDataGroup();
Seguidamente se crean los Data, uno por campo a validar. En este ejemplo se utiliza el SimpleData que es el adecuado para los datos genéricos. Al Data se le añaden los Check. Se puede comprobar que el campo email tiene dos restricciones y el resto tiene solo una.
//For the email
SimpleData theEmail = new SimpleData(this.email, "email");
theEmail.addCheck(new EmailCheck());
theEmail.addCheck(new RegularExpresionCheck(".{1,100}"));
Con esta información ya se puede comprobar si son todos válidos. Conforme los datos sean validos o invalidos se procesaran adecuadamente.
if (inputParameters.check()) {
//All ok return null
return null;
} else {
//There are errors, so using the errorDo and errorDoGroup
//we have the ActionErrors properly configurated
inputParameters.setErrorDo(
new StrutsErrorDo(),
new StrutsErrorDoGroup());
//and return it
return ((StrutsErrorDoGroup) inputParameters.getErrorDoGroup())
.getActionErrors();
}
Si se utilizan los StrutsErrorDo y StrutsErrorDoGroup este código es igual para todos los ActionForm, ya que ambos componentes se encargan de construir los correspondientes ActionError y ActionErrors. El formato de la clave de cada error es de la forma: Para mostrar el mensage de error asociado a esta situación se debería tener en el fichero de properties una clave con este identificativo y como valor el texto descriptivo. Por ejemplo error.email.EmailCheck=El email introducido no es válido El código de tratamiento del Excepciones es también genérico creando un ActionError global, ya que el error no se produce en ningun campo en particular. Normalmente esta situación no se debería dar nunca.
} catch (Exception e) {
ActionError actionError = new ActionError("internalError");
ActionErrors actionErrors = new ActionErrors();
actionErrors.add(ActionErrors.GLOBAL_ERROR, actionError);
return actionErrors;
}
Como se puede observar la validación de los diferentes datos se convierte en algo muy simplificado y mecánico, consistente basicamente en definir los Data necesarios y añadirles las Checks. El resto del trabajo los realizan los diferentes componentes. |