Validazione con Bean: utilizzo di FacesMessage

Forum relativo ai framework per l'utilizzo della tecnologia JSP

Validazione con Bean: utilizzo di FacesMessage

Messaggioda alesslud » mer ott 21, 2009 12:45 pm

Vi proponiamo un esempio che effettua la validazione dei dati immessi in un form direttamente a livello di Bean.

L'esempio riportato sottointende un'approfondita conoscenza di Java.
Allegati
facesbeanvalidation.zip
(14.14 KiB) Scaricato 326 volte
alesslud
Site Admin
 
Messaggi: 779
Iscritto il: mer nov 08, 2006 8:09 am

index.jsp

Messaggioda alesslud » mer ott 21, 2009 12:45 pm

<html>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<f:view>
<head>
<link href="style.css" rel="stylesheet" type="text/css"/>
<f:loadBundle basename="com.aquilasiti.resource.messages" var="res"/>
<title><h:outputText value="#{res.title}"/></title>
</head>
<body>
<h:form>
<h1><h:outputText value="#{res.enterDate}"/></h1>
<h:panelGrid columns="3">
<h:outputText value="#{res.day}"/>
<h:inputText value="#{bean.day}" binding="#{bean.dayInput}"
size="2" required="true"/>
<h:panelGroup/>

<h:outputText value="#{res.month}"/>
<h:inputText value="#{bean.month}" binding="#{bean.monthInput}"
size="2" required="true"/>
<h:panelGroup/>

<h:outputText value="#{res.year}"/>
<h:inputText id="year" value="#{bean.year}"
binding="#{bean.yearInput}" size="4" required="true"
validator="#{bean.validateDate}"/>
<h:message for="year" styleClass="errorMessage"/>
</h:panelGrid>
<h:commandButton value="#{res.submit}" action="submit"/>
</h:form>
</body>
</f:view>
</html>
alesslud
Site Admin
 
Messaggi: 779
Iscritto il: mer nov 08, 2006 8:09 am

result.jsp

Messaggioda alesslud » mer ott 21, 2009 12:46 pm

<html>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<f:view>
<head>
<link href="styles.css" rel="stylesheet" type="text/css"/>
<f:loadBundle basename="com.aquilasiti.resource.messages" var="res"/>
<title><h:outputText value="#{res.title}"/></title>
</head>
<body>
<h:form>
<p><h:outputText value="#{res.validDate}"/></p>
<p>
<h:commandButton value="#{res.back}" action="back"/>
</p>
</h:form>
</body>
</f:view>
</html>
alesslud
Site Admin
 
Messaggi: 779
Iscritto il: mer nov 08, 2006 8:09 am

style.css

Messaggioda alesslud » mer ott 21, 2009 12:46 pm

.errorMessage {
color: green;
}
alesslud
Site Admin
 
Messaggi: 779
Iscritto il: mer nov 08, 2006 8:09 am

web.xml

Messaggioda alesslud » mer ott 21, 2009 12:46 pm

<?xml version="1.0"?>
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.faces</url-pattern>
</servlet-mapping>

<welcome-file-list>
<welcome-file>/index.html</welcome-file>
</welcome-file-list>
</web-app>
alesslud
Site Admin
 
Messaggi: 779
Iscritto il: mer nov 08, 2006 8:09 am

faces-config.xml

Messaggioda alesslud » mer ott 21, 2009 12:47 pm

<?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>
<navigation-rule>
<from-view-id>/index.jsp</from-view-id>
<navigation-case>
<from-outcome>submit</from-outcome>
<to-view-id>/result.jsp</to-view-id>
</navigation-case>
</navigation-rule>

<navigation-rule>
<from-view-id>/result.jsp</from-view-id>
<navigation-case>
<from-outcome>back</from-outcome>
<to-view-id>/index.jsp</to-view-id>
</navigation-case>
</navigation-rule>

<managed-bean>
<managed-bean-name>bean</managed-bean-name>
<managed-bean-class>com.aquilasiti.MyBean</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
</managed-bean>
</faces-config>
alesslud
Site Admin
 
Messaggi: 779
Iscritto il: mer nov 08, 2006 8:09 am

Messages.java

Messaggioda alesslud » mer ott 21, 2009 12:47 pm

package com.aquilasiti.util;

import java.text.MessageFormat;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import javax.faces.application.Application;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;

public class Messages {
public static FacesMessage getMessage(String bundleName, String resourceId,
Object[] params) {
FacesContext context = FacesContext.getCurrentInstance();
Application app = context.getApplication();
String appBundle = app.getMessageBundle();
Locale locale = getLocale(context);
ClassLoader loader = getClassLoader();
String summary = getString(appBundle, bundleName, resourceId,
locale, loader, params);
if (summary == null) summary = "???" + resourceId + "???";
String detail = getString(appBundle, bundleName, resourceId + "_detail",
locale, loader, params);
return new FacesMessage(summary, detail);
}

public static String getString(String bundle, String resourceId,
Object[] params) {
FacesContext context = FacesContext.getCurrentInstance();
Application app = context.getApplication();
String appBundle = app.getMessageBundle();
Locale locale = getLocale(context);
ClassLoader loader = getClassLoader();
return getString(appBundle, bundle, resourceId, locale, loader, params);
}

public static String getString(String bundle1, String bundle2,
String resourceId, Locale locale, ClassLoader loader,
Object[] params) {
String resource = null;
ResourceBundle bundle;

if (bundle1 != null) {
bundle = ResourceBundle.getBundle(bundle1, locale, loader);
if (bundle != null)
try {
resource = bundle.getString(resourceId);
} catch (MissingResourceException ex) {
}
}

if (resource == null) {
bundle = ResourceBundle.getBundle(bundle2, locale, loader);
if (bundle != null)
try {
resource = bundle.getString(resourceId);
} catch (MissingResourceException ex) {
}
}

if (resource == null) return null; // no match
if (params == null) return resource;

MessageFormat formatter = new MessageFormat(resource, locale);
return formatter.format(params);
}

public static Locale getLocale(FacesContext context) {
Locale locale = null;
UIViewRoot viewRoot = context.getViewRoot();
if (viewRoot != null) locale = viewRoot.getLocale();
if (locale == null) locale = Locale.getDefault();
return locale;
}

public static ClassLoader getClassLoader() {
ClassLoader loader = Thread.currentThread().getContextClassLoader();
if (loader == null) loader = ClassLoader.getSystemClassLoader();
return loader;
}
}
alesslud
Site Admin
 
Messaggi: 779
Iscritto il: mer nov 08, 2006 8:09 am

messages.properties

Messaggioda alesslud » mer ott 21, 2009 12:47 pm

invalidDate=Data invalida.
invalidDate_detail=La data inserita non è valida.
title=Validazione a livello di Bean
enterDate=Inserisci un valore.
day=Giorno
month=Mese
year=Anno
submit=Invia
validDate=La data inserita è valida.
back=Indietro
alesslud
Site Admin
 
Messaggi: 779
Iscritto il: mer nov 08, 2006 8:09 am

MyBean.java

Messaggioda alesslud » mer ott 21, 2009 12:47 pm

package com.aquilasiti;

import java.text.SimpleDateFormat;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.component.UIInput;
import javax.faces.context.FacesContext;
import javax.faces.validator.ValidatorException;

public class MyBean {
private int day;
private int month;
private int year;
private UIInput dayInput;
private UIInput monthInput;
private UIInput yearInput;


public int getDay() {
return day;
}

public void setDay(int newValue) {
day = newValue;
}


public int getMonth() {
return month;
}

public void setMonth(int month) {
this.month = month;
}


public int getYear() {
return year;
}

public void setYear(int year) {
this.year = year;
}


public UIInput getDayInput() {
return dayInput;
}

public void setDayInput(UIInput dayInput) {
this.dayInput = dayInput;
}


public UIInput getMonthInput() {
return monthInput;
}

public void setMonthInput(UIInput monthInput) {
this.monthInput = monthInput;
}


public UIInput getYearInput() {
return yearInput;
}

public void setYearInput(UIInput yearInput) {
this.yearInput = yearInput;
}

public void validateDate(FacesContext context, UIComponent component,
Object value) {
int d = ((Integer) dayInput.getLocalValue()).intValue();
int m = ((Integer) monthInput.getLocalValue()).intValue();
int y = ((Integer) value).intValue();
try {
this.validateDate(d, m, y);
} catch (ValidatorException ex) {
throw new ValidatorException(ex.getFacesMessage());
}
}

private void validateDate(int d, int m, int y) throws ValidatorException {
String data = d + "/" + m + "/" + y;
try {
this.convertStringToDate(data);
} catch (ValidatorException e) {
throw new ValidatorException(e.getFacesMessage());
}
}

public java.util.Date convertStringToDate(String data) {
java.util.Date d = null;
try {
String formatoData = data.indexOf("/") != -1 ? "dd/MM/yyyy"
: "yyyyMMdd";
SimpleDateFormat sdf = new SimpleDateFormat(formatoData);
sdf.setLenient(false);
d = sdf.parse(data);

} catch (Exception e) {
FacesMessage message = com.aquilasiti.util.Messages.getMessage(
"com.aquilasiti.resource.messages", "invalidDate", null);
throw new ValidatorException(message);
}
return d;
}
}
alesslud
Site Admin
 
Messaggi: 779
Iscritto il: mer nov 08, 2006 8:09 am


Torna a JSF e Struts

Chi c’è in linea

Visitano il forum: Nessuno e 1 ospite

cron