VALIDACIONES Y CONVERSIONES EN JSF
Introducción
En este tutorial veremos como JSF proporciona mecanismos
para el formateo, conversión y validación de los componentes; veremos como estos
mecanismos pueden ser extendidos de forma sencilla para adaptarlos a nuestras
necesidades. La primera parte del
tutorial estará dedicada al formateo y conversión y la segunda a la Validación.
Para entender en qué momento de la vida de una página JSF se
producen las conversiones y validaciones de los componentes del formulario,
quizá nos sea de ayuda el siguiente diagrama:
JSF proporciona dos mecanismos separados que nos ayuda a
validar los valores introducidos por los usuarios a la hora de submitir los
formularios:
- El
primer mecanismo es el de conversión
y está definido por el interfaz javax.faces.convert.Converter
y sus múltiples implementaciones. Las
conversiones aseguran que el tipo de un dato introducido en un formulario
JSF sea el correcto, es decir, que el dato tipo cadena del formulario
corresponde con el tipo JAVA esperado, y que está especificado en la
propiedad correspondiente del bean. Los Conversores (implementaciones de la interfaz Converter) son los componentes que
se encargan de hacer estas transformaciones (cadena>Tipo JAVA y viceversa).
JSF invoca a los Conversores
antes de efectuar las validaciones y por lo tanto antes de aplicar los
valores introducidos a las propiedades del bean. En el caso de que un dato
tipo cadena no se corresponda con el tipo JAVA apropiado, el Conversor correspondiente lanzará
un ConversionException y el
componente se marcará como invalidado. - El segundo
mecanismo es el de validación y
está definido por la interfaz javax.faces.validator.Validator
y sus múltiples implementaciones. El proceso de validación se asegura que
el dato introducido en el correspondiente componente es correcto según la
lógica de la aplicación. El proceso de validación ocurre antes de que el
FrameWork asigne los valores introducidos en el formulario a las
propiedades del bean y justo después de que se hayan aplicado las
conversiones, en el caso de que haya. Las
validaciones aseguran que un dato introducido en un formulario JSF tenga
un valor correcto.
Los mensajes que lanzan tanto los Conversores como lo
Validadores en el caso de excepción se pueden mostrar en el formulario
correspondiente a través de la etiqueta messages.
A continuación vamos a ver 4 casos prácticos:
- Un
ejemplo de conversión utilizando un conversor estándar de JSF. - Un
ejemplo de conversión realizada por un conversor que creemos nosotros. - Un
ejemplo de validación utilizando un validador estándar de JSF. - Un
ejemplo de validación utilizando un validador creado por nosotros.
Herramientas utilizadas
- Sistema
operativo: Windows XP Professional. - Servidor
Web: Apache Tomcat 5.5.9 - Entorno
de desarrollo: Eclipse 3.1.1 con ExadelStudio-3[1].0.5
Preparamos el entorno
Seguiremos los siguientes pasos:
1.
Creamos un
nuevo proyecto JSF en Eclipse, al que llamaremos PruebaValidaciones. Indicaremos durante la creación que el entorno JSF
es MyFaces 1.1.0. La estructura de directorios que nos queda es la siguiente:
2.
Creamos la
página index.jsp en el directorio WebContent: redireccionará a la página home.jsf
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<%@ taglib uri=”http://myfaces.apache.org/extensions” prefix=”t” %> <!doctype html public “-//w3c//dtd html 4.0 transitional//en”> <html> <head>AUTENTIA- TUTORIAL CONVERSIONES-VALIDACIONES</head> <body> <jsp:forward page=”home.jsf” /> </body> </html> |
3.
Creamos la
página home.jsp en el directorio WebContent: esta página tendrá enlaces a los diferentes ejemplos
que vamos a hacer:
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 |
<%@ taglib uri=”http://java.sun.com/jsf/html” prefix=”h”%> <%@ taglib uri=”http://java.sun.com/jsf/core” prefix=”f”%> <%@ taglib uri=”http://myfaces.apache.org/tomahawk” prefix=”t”%> <html> <head> <title>AUTENTIA-Tutorial de Conversiones y validaciones</title> </head> <body> <f:view> <h:panelGrid id=”cabecera” columns=”2″ styleClass=”cabecera” > <t:graphicImage id=”logo” url=”img/demo_logo.gif” alt=”AUTENTIA – Soluciones Reales para su empresa”/> <f:verbatim> </f:verbatim> </h:panelGrid> <br/> <h:outputLink value=”conversion_estandar.jsf”><f:verbatim>Conversión estándar</f:verbatim></h:outputLink> <br/> <h:outputLink value=”conversion_nuestra.jsf” ><f:verbatim>Nuestra conversión</f:verbatim></h:outputLink> <br/> <br /> <h:outputLink value=”validacion_estandar.jsf” ><f:verbatim>Validación estándar</f:verbatim></h:outputLink> <br/> <h:outputLink value=”validacion_nuestra.jsf” ><f:verbatim>Nuestra validación</f:verbatim></h:outputLink> <br/> <br /> </f:view> </body> </html> |
Y si probamos lo poco que hemos hecho:
Los ejemplos que vamos a hacer a partir de este momento partirán de esta
página.
Primer ejemplo:
usando un conversor estándar
Antes
de nada debemos tener en cuenta que los conversores estándar que proporciona
JSF se dividen en conversores a tipos numéricos (NumberConverter) y conversores a tipos Fecha (DateTimeConverter)
Existen
dos formas de indicar que el valor de un determinado componente de nuestra
página va a ser “convertido”:
·
Añadiendo el
atributo converter=”#{identificador_conversor}”
al componente. Sólo los componentes del tipo UIInput (inputText, inputSecret, inputHidden) y outputText aceptan esta propiedad. Un ejemplo sería el siguiente:
1 |
<h:inputText converter=”#{Double}” value=”#{modifyInvoicePage.invoice.amount}”/> |
JSF deja a nuestra
disposición los siguientes conversores estándar:
TIPO DE CONVERSOR |
IDENTIFICADOR DEL CONVERSOR |
BigDecimalConverter |
BigDecimal |
BigIntegerConverter |
BigInteger |
NumberConverter |
Number |
IntegerConverter |
Integer |
ShortConverter |
Short |
ByteConverter |
Byte |
CharacterConverter |
Character |
FloatConverter |
Float |
DoubleConverter |
Double |
BooleanConverter |
Boolean |
DateTimeConverter |
DateTime |
·
Incluyendo <f:convertNumber [lista_atributos]/> o <f:convertDateTime [lista_atributos]/> dentro de la
invocación al componente, como por ejemplo:
1 2 3 4 5 |
<h:inputText value=”#{modifyInvoicePage.invoice.amount}”> <f:convertNumber type=”currency”/> </h:inputText> |
1 2 3 4 5 |
<h:inputText id=”invoiceDate” value=”#{modifyInvoicePage.invoice.invoiceDate}”> <f:convertDateTime pattern=”M/d/yyyy”/> </h:inputText> |
Los
atributos disponibles para tipos number
son:
NOMBRE DEL ATRIBUTO |
TIPO |
currencyCode |
String |
currencySymbol |
String |
groupingUsed |
boolean |
integerOnly |
boolean |
locale |
java.util.Locale |
maxFractionDigits |
int |
maxIntegerDigits |
Int |
minFractionDigits |
Int |
minIntegerDigits |
int |
pattern |
String |
type |
String |
Y los
disponibles para tipos DateTime:
NOMBRE DEL ATRIBUTO |
TIPO |
dateStyle |
String |
parseLocale |
String o Locale |
pattern |
String |
timeStyle |
String |
timeZone |
String o TimeZone |
type |
String |
1.
Vamos a crear por fin el bean
La clase se llama com.autentia.tutorialValidacion.GestionUsuariosBean.java, cuelga del
directorio JavaSource y de momento tiene la siguiente pinta:
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 |
package com.autentia.tutorialValidacion; import java.math.BigDecimal; import java.util.Date; /** * Bean para probar conversiones y validaciones en JSF * @author AUTENTIA */ public class GestionUsuariosBean { /** Nombre del usuario */ private String nombre; /** Edad del usuario */ private int edad; /** Fecha de nacimiento */ private Date fechaNacimiento; /** Sueldo */ private BigDecimal sueldo; /** * Constructor */ public GestionUsuariosBean(){} public int getEdad() { return edad; } public void setEdad(int edad) { this.edad = edad; } public Date getFechaNacimiento() { return fechaNacimiento; } public void setFechaNacimiento(Date fechaNacimiento) { this.fechaNacimiento = fechaNacimiento; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public BigDecimal getSueldo() { return sueldo; } public void setSueldo(BigDecimal sueldo) { this.sueldo = sueldo; } } |
Y
lo registramos en el fichero descriptor de JSF (WEB-INF/validaciones-config.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 |
<?xml version=”1.0″?> <!DOCTYPE faces-config PUBLIC “-//Sun Microsystems, Inc.//DTD JavaServer Faces Config 1.0//EN” “http://java.sun.com/dtd/web-facesconfig_1_0.dtd”> <faces-config> <managed-bean> <description>Bean para probar conversiones/validaciones</description> <managed-bean-name>gestionUsuariosBean</managed-bean-name> <managed-bean-class> com.autentia.tutorialValidacion.GestionUsuariosBean </managed-bean-class> <managed-bean-scope>session</managed-bean-scope> </managed-bean> </faces-config> |
2.
Creamos la página
La
llamamos conversion_estandar.jsp y
cuelga de WebContent:
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 |
<%@ taglib uri=”http://java.sun.com/jsf/html” prefix=”h” %> <%@ taglib uri=”http://java.sun.com/jsf/core” prefix=”f” %> <%@ taglib uri=”http://myfaces.apache.org/extensions” prefix=”t” %> <html> <head> <title>AUTENTIA – TUTORIAL VALIDACIONES/CONVERSIONES</title> <link rel=”stylesheet” type=”text/css” href=”css/estilos.css”> </head> <body> <f:view> <h:form id=”idUsuarios” name=”gestionUsuariosBean”> <h:messages id=”messageList” styleClass=”error” showSummary=”true” showDetail=”true” /> <h:panelGrid columns=”2″ styleClass=”gestionUsuariosFormTable” headerClass=”gestionUsuariosFormHeader” footerClass=”gestionUsuariosFormFooter” columnClasses=”gestionUsuariosFormLabels, gestionUsuariosFormInputs” width=”600″> <!– Nombre –> <h:outputLabel for=”login” value=”Nombre”/> <h:panelGroup> <h:inputText id=”nombre” styleClass=”CajasTexto” size=”30″ maxlength=”100″ value=”#{gestionUsuariosBean.nombre}” /> </h:panelGroup> <!– Edad –> <h:outputLabel for=”edad” value=”Edad”/> <h:panelGroup> <h:inputText id=”laEdad” converter=”#{Integer}” styleClass=”CajasTexto” size=”30″ maxlength=”3″ value=”#{gestionUsuariosBean.edad}” /> </h:panelGroup> <!– Fecha de nacimiento –> <h:outputLabel for=”fechaNacimiento” value=”Fecha de nacimiento”/> <h:panelGroup> <h:inputText id=”fecha” styleClass=”CajasTexto” size=”30″ maxlength=”12″ value=”#{gestionUsuariosBean.fechaNacimiento}”> <f:convertDateTime pattern=”dd/MM/yyyy”/> </h:inputText> </h:panelGroup> <!– Sueldo –> <h:outputLabel for=”sueldo” value=”Sueldo”/> <h:panelGroup> <h:inputText converter=”#{BigDecimal}” styleClass=”CajasTexto” size=”30″ maxlength=”15″ id=”idSueldo” value=”#{gestionUsuariosBean.sueldo}” /> </h:panelGroup> <h:panelGroup> <h:commandButton action=”resultado_conversion” value=”Validar” /> <f:verbatim> </f:verbatim> </h:panelGroup> </h:panelGrid> </h:form> </f:view> </body> </html> |
Como
vemos, es muy sencillo utilizar los conversores estándar y cualquier
explicación sobra. Para que el botón de Validar
funcione, debemos añadir la correspondiente regla de navegación en el fichero WEB-INF/validaciones-config.xml:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
… .. <navigation-rule> <from-view-id>/conversion_estandar.jsp</from-view-id> <navigation-case> <from-outcome>resultado_conversion</from-outcome> <to-view-id>/resultado_conversion.jsp</to-view-id> <redirect/> </navigation-case> </navigation-rule> … … |
Y
para que el ejemplo nos quede chulo, creamos la página que dice que dice que
todo ha ido bien y muestra los valores introducidos por el usuario:
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 |
<%@ taglib uri=”http://java.sun.com/jsf/html” prefix=”h” %> <%@ taglib uri=”http://java.sun.com/jsf/core” prefix=”f” %> <%@ taglib uri=”http://myfaces.apache.org/extensions” prefix=”t” %> <html> <head> <title>AUTENTIA – TUTORIAL VALIDACIONES/CONVERSIONES</title> <link rel=”stylesheet” type=”text/css” href=”css/estilos.css”> </head> <body> <f:view> <h:form id=”idUsuarios” name=”gestionUsuariosBean”> <h:messages id=”messageList” styleClass=”error” showSummary=”true” showDetail=”true” /> <h:panelGrid columns=”2″ styleClass=”gestionUsuariosFormTable” headerClass=”gestionUsuariosFormHeader” footerClass=”gestionUsuariosFormFooter” columnClasses=”gestionUsuariosFormLabels, gestionUsuariosFormInputs” width=”600″> <!– Nombre –> <h:outputLabel for=”login” value=”Nombre”/>: <h:panelGroup> <h:outputText value=”#{gestionUsuariosBean.nombre}”/> </h:panelGroup> <!– Edad –> <h:outputLabel for=”edad” value=”Edad”/> <h:panelGroup> <h:outputText value=”#{gestionUsuariosBean.edad}”/> </h:panelGroup> <!– Fecha de nacimiento –> <h:outputLabel for=”fechaNacimiento” value=”Fecha de nacimiento”/> <h:panelGroup> <h:outputText value=”#{gestionUsuariosBean.fechaNacimiento}”/> </h:panelGroup> <!– Sueldo –> <h:outputLabel for=”sueldo” value=”Sueldo”/> <h:panelGroup> <h:outputText value=”#{gestionUsuariosBean.sueldo}”/> </h:panelGroup> <h:panelGroup> <h:commandButton action=”home” value=”Volver” /> <f:verbatim> </f:verbatim> </h:panelGroup> </h:panelGrid> </h:form> </f:view> </body> </html> |
Por
ultimo, para completar el ejemplo, añadimos la navegabilidad para el botón de volver, que retornará a la página home.jsp:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
… .. <navigation-rule> <from-view-id>/resultado_conversion.jsp</from-view-id> <navigation-case> <from-outcome>home</from-outcome> <to-view-id>/home.jsp</to-view-id> <redirect/> </navigation-case> </navigation-rule> … … |
3.
Probamos
Vamos
a introducir todos los valores incorrectos y vemos cual es el resultado:
|
|
Y
ahora con valores correctos (bueno, menos la edad y el sueldo, pero eso no hay
forma que lo conozcan los conversores de JSF ;-) ):
|
|
Segundo ejemplo:
creando nuestro propio conversor
Para
crear nuestro propio conversor, debemos seguir los siguientes pasos:
o Crear una clase que implemente la interfaz javax.faces.convert.Converter.
o Implementar el método getAsObject, que convierte el valor del componente que tengamos en
la página (tipo cadena) a un objeto (tipo JAVA que requiera la aplicación).
o Implementar el método getAsString, que convierte el objeto (tipo JAVA de nuestra
aplicación) a tipo cadena (requerido por la página).
o Registrar el nuevo conversor en el contexto de JSF.
o Utilizarlo en la página insertando dentro del
componente cuyo valor queramos convertir el tag <f:converter>.
1.
Qué va hacer nuestro conversor
Va a desglosar un número de teléfono de tipo:
91-888 33 66
En dos partes:
Prefijo = 91
Número de teléfono= 888 33 66
El conversor lanzará excepciones si:
·
No se introduce el guión para separar el prefijo del número
·
Si el prefijo no consta de 2 números
·
Si el número no consta de 7 números. Los espacios entre los números se
ignorarán
2.
Creamos el conversor
Como hemos indicado antes, debe implementar la interfaz Converter y los métodos getAsObject
y getAsString. Vamos a llamarlo TelefonoConverter. Para este ejemplo he
utilizado la librería commons-lang de
Yakarta que nos la podemos descargar desde la página http://jakarta.apache.org/site/downloads/downloads_commons-lang.cgi.
La he incorporado al paquete lib y he actualizado el classpath de la aplicación.
El método getAsObject va a devolver la instancia
de una nueva clase Telefono.java que
tiene la siguiente pinta:
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 |
package com.autentia.tutorialValidacion; /** * Clase que representa un teléfono * @author AUTENTIA */ public class Telefono { /** El prefijo */ private String prefijo; /** El número de teléfono */ private String numero; /** * Constructor */ public Telefono(){} public String getNumero() { return numero; } public void setNumero(String numero) { this.numero = numero; } public String getPrefijo() { return prefijo; } public void setPrefijo(String prefijo) { this.prefijo = prefijo; } /** * Devuelve el número de teléfono como un String */ public String toString() { StringBuffer elNumero = new StringBuffer(); elNumero.append(prefijo); elNumero.append(“-“); elNumero.append(numero); return elNumero.toString(); } } |
Y por fin la clase TelefonoConverter:
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 |
package com.autentia.tutorialValidacion; import javax.faces.application.FacesMessage; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.convert.Converter; import javax.faces.convert.ConverterException; import org.apache.commons.lang.StringUtils; /** * Conversor de números de teléfono * @author AUTENTIA */ public class TelefonoConverter implements Converter { /** * Devuelve la representación Telefono de JAVA a partir del valor de un componente JSF */ public Object getAsObject(FacesContext context, UIComponent component, String value) throws ConverterException { Telefono telefono = null; if(!StringUtils.isEmpty(value)) { telefono = new Telefono(); String valores[] = StringUtils.split(value,”-“); if(valores.length!=2) throw new ConverterException(new FacesMessage(“El número de teléfono debe tener el siguiente formato: ‘pp-nnn nn nn’, donde pp es el prefijo y nnn nn nn es el número”)); if(valores[0].length()!=2) throw new ConverterException(new FacesMessage(“El prefijo del número de teléfono debe tener de tipo NN”)); String elNumero = StringUtils.remove(valores[1],’ ‘); if(elNumero.length()!=7) throw new ConverterException(new FacesMessage(“El número de teléfono debe ser de tipo NNN NN NN”)); telefono.setPrefijo(valores[0]); telefono.setNumero(valores[1]); } return telefono; } /** * Devuelve la representacion cadena de un teléfono */ public String getAsString(FacesContext context, UIComponent component, Object value) throws ConverterException { return value.toString(); } } |
3.
Adaptamos el bean GestionUsuariosBean para probar
nuestro conversor
Añadimos un nuevo atributo de tipo Telefono
al bean:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
... ... /** Teléfono */ private Telefono telefono; ... ... public Telefono getTelefono() { return telefono; } public void setTelefono(Telefono telefono) { this.telefono = telefono; } ... ... |
4.
Registramos el nuevo conversor en el contexto de JSF
Para ello editamos el fichero WEB-INF/validaciones-config.xml
y ponemos lo siguiente:
1 2 3 4 5 6 7 8 9 10 11 |
...... <converter> <converter-id>autentia.telefonoConverter</converter-id> <converter-class>com.autentia.tutorialValidacion.TelefonoConverter</converter-class> </converter> ...... |
5.
Creamos la página conversión_nuestra.jsp
que cuelga de WebContent:
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 |
<%@ taglib uri=”http://java.sun.com/jsf/html” prefix=”h” %> <%@ taglib uri=”http://java.sun.com/jsf/core” prefix=”f” %> <%@ taglib uri=”http://myfaces.apache.org/extensions” prefix=”t” %> <html> <head> <title>AUTENTIA – TUTORIAL VALIDACIONES/CONVERSIONES</title> <link rel=”stylesheet” type=”text/css” href=”css/estilos.css”> </head> <body> <f:view> <h:form id=”idUsuarios” name=”gestionUsuariosBean”> <h:messages id=”messageList” styleClass=”error” showSummary=”true” showDetail=”true” /> <h:panelGrid columns=”2″ styleClass=”gestionUsuariosFormTable” headerClass=”gestionUsuariosFormHeader” footerClass=”gestionUsuariosFormFooter” columnClasses=”gestionUsuariosFormLabels, gestionUsuariosFormInputs” width=”600″> <!– Nombre –> <h:outputLabel for=”login” value=”Nombre”/> <h:panelGroup> <h:inputText id=”nombre” styleClass=”CajasTexto” size=”30″ maxlength=”100″ value=”#{gestionUsuariosBean.nombre}” /> </h:panelGroup> <!– Numero telefono –> <h:outputLabel for=”telefono” value=”Numero de telefono”/> <h:panelGroup> <h:inputText id=”telefono” styleClass=”CajasTexto” size=”30″ maxlength=”12″ value=”#{gestionUsuariosBean.telefono}”> <f:converter converterId=”autentia.telefonoConverter” /> </h:inputText> </h:panelGroup> <h:panelGroup> <h:commandButton action=”resultado_conversion_nuestra” value=”Validar” /> <f:verbatim> </f:verbatim> </h:panelGroup> </h:panelGrid> </h:form> </f:view> </body> </html> |
Y también añadimos la navegabilidad necesaria para que, una vez
convertido el valor, la aplicación vaya a la página de resultados (resultado_conversion_nuestra) y para que
desde esta página de resultados podamos volver a la página home (home)
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 |
……… <navigation-rule> <from-view-id>/conversion_nuestra.jsp</from-view-id> <navigation-case> <from-outcome>resultado_conversion_nuestra</from-outcome> <to-view-id>/resultado_conversion_nuestra.jsp</to-view-id> <redirect/> </navigation-case> </navigation-rule> <navigation-rule> <from-view-id>/resultado_conversion_nuestra.jsp</from-view-id> <navigation-case> <from-outcome>home</from-outcome> <to-view-id>/home.jsp</to-view-id> <redirect/> </navigation-case> </navigation-rule> ……….. |
6.
Y probamos:
|
|
|
|
|
|
Tercer ejemplo:
utilizando validaciones estándar de JSF
En la primera parte
de este tutorial hemos visto como los Conversores
pueden cubrir gran parte de la funcionalidad necesaria para validar que los
valores introducidos por los usuarios en un formulario JSF sean correctos.
En adición, los Validadores pueden realizar validaciones
más genéricas durantes la fase de Validación. Estos componentes implementan la
interfaz javax.faces.validator.Validator,
que contiene un único método validate(). JSF
provee un conjunto de Validadores
estándar que se describen en la tabla siguiente:
CLASE DE VALIDADOR |
TAG JSF |
ATRIBUTOS |
DESCRIPCIÓN |
|
DoubleRangeValidator |
validateDoubleRange |
minimum,maximum |
Valida que el valor del componente sea mayor |
|
LengthValidator |
validateLength |
minimum,maximum |
Valida que la longitud del valor del |
|
LongRangeValidator |
validateLongRange |
minimum,maximum |
Valida que el valor del componente sea mayor |
|
Además, myFaces
proporciona los siguientes Validadores
como adición a los anteriores:
CLASE DE VALIDADOR |
TAG JSF |
ATRIBUTOS |
DESCRIPCIÓN |
|
EmailValidator |
validateEmail |
|
Valida que el valor del componente tenga un |
|
CreditCardValidator |
validateCreditCard |
none(true|false), amex(true|false), visa(true|false), mastercard(true|false), |
Valida que el valor del componente corresponde |
|
RegExprValidator |
validateRegExpr |
pattern |
Valida que el valor del componente se |
|
EqualValidator |
validateEqual |
for |
Valida que el valor del componente sea |
1.
Preparamos el bean GestionUsuariosBean para el ejemplo
Vamos a efectuar las siguientes validaciones:
·
Que la edad del usuario esté comprendida entre 5 y 100 años
·
Que el nombre no tenga más de 40 caracteres
·
Que el nuevo atributo password
debe ser igual que el campo repetición de password
Por lo tanto, al bean sólo le falta un nuevo
atributo password:
… … /** Password del usuario */ private String password; public String getPassword() { return } public void setPassword(String password) { this.password } … … |
2.
Creamos la página
La
llamaremos validación_estandar.jsp y
colgará de WebContent:
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 |
<%@ taglib uri=”http://java.sun.com/jsf/html” prefix=”h” %> <%@ taglib uri=”http://java.sun.com/jsf/core” prefix=”f” %> <%@ taglib uri=”http://myfaces.apache.org/extensions” prefix=”t” %> <html> <head> <title>AUTENTIA – TUTORIAL VALIDACIONES/CONVERSIONES</title> <link rel=”stylesheet” type=”text/css” href=”css/estilos.css”> </head> <body> <f:view> <h:form id=”idUsuarios” name=”gestionUsuariosBean”> <h:messages id=”messageList” styleClass=”error” showSummary=”true” showDetail=”true” /> <h:panelGrid columns=”2″ styleClass=”gestionUsuariosFormTable” headerClass=”gestionUsuariosFormHeader” footerClass=”gestionUsuariosFormFooter” columnClasses=”gestionUsuariosFormLabels, gestionUsuariosFormInputs” width=”600″> <!– Nombre –> <h:outputLabel for=”login” value=”Nombre”/> <h:panelGroup> <h:inputText id=”nombre” styleClass=”CajasTexto” size=”30″ maxlength=”100″ value=”#{gestionUsuariosBean.nombre}”> <f:validateLength maximum=”50″ /> </h:inputText> </h:panelGroup> <!– Edad –> <h:outputLabel for=”edad” value=”Edad”/> <h:panelGroup> <h:inputText id=”laEdad” converter=”#{Integer}” styleClass=”CajasTexto” size=”30″ maxlength=”3″ value=”#{gestionUsuariosBean.edad}”> <f:validateLongRange maximum=”100″ minimum=”5″/> </h:inputText> </h:panelGroup> <!– Password –> <h:outputLabel for=”password” value=”Password”/> <h:panelGroup> <h:inputSecret id=”password” styleClass=”CajasTexto” size=”30″ maxlength=”12″ value=”#{gestionUsuariosBean.password}” /> </h:panelGroup> <!– Repetición de password –> <h:outputLabel for=”password” value=”Repetición de password”/> <h:panelGroup> <h:inputSecret id=”passwordRepe” styleClass=”CajasTexto” size=”30″ maxlength=”12″ value=”#{gestionUsuariosBean.password}”> <t:validateEqual for=”password” /> </h:inputSecret> </h:panelGroup> <h:panelGroup> <h:commandButton action=”resultado_validacion” value=”Validar” /> <f:verbatim> </f:verbatim> </h:panelGroup> </h:panelGrid> </h:form> </f:view> </body> </html> |
Añadimos
la navegación en el fichero WEB-INF/validaciones-config.xml
para que el botón Validar vaya al
sitio adecuado:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
… … <navigation-rule> <from-view-id>/validacion_estandar.jsp</from-view-id> <navigation-case> <from-outcome>resultado_validacion</from-outcome> <to-view-id>/resultado_validacion.jsp</to-view-id> <redirect/> </navigation-case> </navigation-rule> … … |
3.
El resultado
|
|
|
|
|
|
Cuarto ejemplo:
creando nuestro propio Validador
Para
crear nuestro propio Validador,
debemos seguir los siguientes pasos:
·
Crear una clase
que implemente la interfaz javax.faces.validator.Validator.
·
Implementar el
método validate.
·
Registrar el
nuevo validador en el contexto de JSF.
·
Utilizarlo en la
página insertando dentro del componente cuyo valor queramos validar el tag <f:validator>.
1.
Qué va a validar nuestro Validador
Que
el valor de un componente se corresponde un número de NIF válido.
El
algoritmo que voy a utilizar para validar el NIF es el siguiente
·
Compruebo que el
valor a validar tiene una longitud igual a 9. Los primeros 8 caracteres deben
ser números (corresponden al DNI) y el último debe ser una letra (la del NIF)
·
Almaceno la
siguiente lista de letras en una variable:
“TRWAGMYFPDXBNJZSQVHLCKE”
·
Calculo el
módulo entero de 23.
·
Recupero de la
lista de letras la que se encuentra en la posición resultado de efectuar el
módulo entero de 23
2.
Creamos el Validador
Como
dijimos anteriormente, debe ser una implementación del interfaz Validator:
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 |
package com.autentia.tutorialValidacion; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.faces.application.FacesMessage; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.validator.Validator; import javax.faces.validator.ValidatorException; import org.apache.commons.lang.StringUtils; /** * Validador de NIF * @author AUTENTIA */ public class NifValidator implements Validator { /** * Efectúa el proceso de validación */ public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException { // Si el valor es null, lo transformamos en un valor vacío String valor = StringUtils.defaultString((String)value); // el valor debe tener 9 posiciones, de las cuales las primeras deben ser dígitos y la última letra valor=valor.toUpperCase(); Pattern mask = Pattern.compile(“[0-9]{8,8}[A-Z]”); Matcher matcher = mask.matcher(valor); if(!matcher.matches()) throw new ValidatorException(new FacesMessage(“El componente ” + component.getId() + “ no contiene un NIF válido. Las 8 primeras posiciones deben ser numéricas”)); String dni=valor.substring(0,8); String digitoControl = valor.substring(8,9); // Calculamos la letra de control String letras = “TRWAGMYFPDXBNJZSQVHLCKE”; int posicion_modulo = Integer.parseInt(dni)%23; String digitoControlCalculado = letras.substring(posicion_modulo,posicion_modulo+1); if(!digitoControl.equalsIgnoreCase(digitoControlCalculado)) throw new ValidatorException(new FacesMessage(“El componente ” + component.getId() + ” no contiene un NIF válido”)); } } |
3.
Registramos el nuevo Validador en el contexto de JSF.
Para
ello, editamos el fichero descriptor WEB-INF/validaciones-config.xml
e insertamos las siguientes líneas:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
… <validator> <validator-id>autentia.nifValidator</validator-id> <validator-class> com.autentia.tutorialValidacion.NifValidator </validator-class> </validator> … |
4.
Creamos la página
La
llamaremos validacion_nuestra.jsp y colgará de WebContent; su contenido es el siguiente:
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 |
<%@ taglib uri=”http://java.sun.com/jsf/html” prefix=”h” %> <%@ taglib uri=”http://java.sun.com/jsf/core” prefix=”f” %> <%@ taglib uri=”http://myfaces.apache.org/extensions” prefix=”t” %> <html> <head> <title>AUTENTIA – TUTORIAL VALIDACIONES/CONVERSIONES</title> <link rel=”stylesheet” type=”text/css” href=”css/estilos.css”> </head> <body> <f:view> <h:form id=”idUsuarios” name=”gestionUsuariosBean”> <h:messages id=”messageList” styleClass=”error” showSummary=”true” showDetail=”true” /> <h:panelGrid columns=”2″ styleClass=”gestionUsuariosFormTable” headerClass=”gestionUsuariosFormHeader” footerClass=”gestionUsuariosFormFooter” columnClasses=”gestionUsuariosFormLabels, gestionUsuariosFormInputs” width=”600″> <!– Nombre –> <h:outputLabel for=”login” value=”Nombre”/> <h:panelGroup> <h:inputText id=”nombre” styleClass=”CajasTexto” size=”30″ maxlength=”100″ value=”#{gestionUsuariosBean.nombre}”> <f:validateLength maximum=”50″ /> </h:inputText> </h:panelGroup> <!– Nif –> <h:outputLabel for=”nif” value=”Nif”/> <h:panelGroup> <h:inputText id=”elNif” styleClass=”CajasTexto” size=”30″ maxlength=”10″ value=”#{gestionUsuariosBean.nif}” required=”true”> <f:validator validatorId=”autentia.nifValidator”/> </h:inputText> </h:panelGroup> <h:panelGroup> <h:commandButton action=”resultado_validacion_nuestra” value=”Validar” /> <f:verbatim> </f:verbatim> </h:panelGroup> </h:panelGrid> </h:form> </f:view> </body> </html> |
Añadimos
en WEB-INF/validaciones-config.xml la
navegabilidad para el botón Validar:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
… <navigation-rule> <from-view-id>/validacion_nuestra.jsp</from-view-id> <navigation-case> <from-outcome>resultado_validacion_nuestra</from-outcome> <to-view-id>/resultado_validacion_nuestra.jsp</to-view-id> <redirect/> </navigation-case> </navigation-rule> … |
Y
creamos la página de resultados WebContent/resultado_validacion_nuestra.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 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 |
<%@ taglib uri=”http://java.sun.com/jsf/html” prefix=”h” %> <%@ taglib uri=”http://java.sun.com/jsf/core” prefix=”f” %> <%@ taglib uri=”http://myfaces.apache.org/extensions” prefix=”t” %> <html> <head> <title>AUTENTIA – TUTORIAL VALIDACIONES/CONVERSIONES</title> <link rel=”stylesheet” type=”text/css” href=”css/estilos.css”> </head> <body> <f:view> <h:form id=”idUsuarios” name=”gestionUsuariosBean”> <h:messages id=”messageList” styleClass=”error” showSummary=”true” showDetail=”true” /> <h:panelGrid columns=”2″ styleClass=”gestionUsuariosFormTable” headerClass=”gestionUsuariosFormHeader” footerClass=”gestionUsuariosFormFooter” columnClasses=”gestionUsuariosFormLabels, gestionUsuariosFormInputs” width=”600″> <!– Nombre –> <h:outputLabel for=”login” value=”Nombre”/>: <h:panelGroup> <h:outputText value=”#{gestionUsuariosBean.nombre}”/> </h:panelGroup> <!– Nif –> <h:outputLabel for=”nif” value=”Nif”/> <h:panelGroup> <h:outputText value=”#{gestionUsuariosBean.nif}”/> </h:panelGroup> <h:panelGroup> <h:commandButton action=”home” value=”Volver” /> <f:verbatim> </f:verbatim> </h:panelGroup> </h:panelGrid> </h:form> </f:view> </body> </html> |
5.
Probamos
Desplegamos
la aplicación en Tomcat y vemos cual es el resultado:
|
|
|
|
———————————————————–
Si
necesita ayuda al plantear sus soluciones tecnológicas no dude en contactar con
nosotros a través de nuestra web www.autentia.com.
Estaremos encantados de ayudarle en su problema poniendo a su disposición a
nuestros mejores expertos a precios asequibles.
Que tal, me gusto mucho el texto, aprendi varias cosas. Muchas gracias!
Estuvo excelente aun util a al fecha