Pages

Wednesday, August 4, 2010

Spring - Internationalization i18N


In Spring MVC application, comes with few “LocaleResolver” to support the internationalization or multiple languages features. In this tutorial, it shows a simple user form page, display the message from properties file, and change the locale based on the selected language link.

Web.xml



<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<servlet>
<servlet-name>disp</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>disp</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/disp-servlet.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<welcome-file-list>
<welcome-file>redirect.jsp</welcome-file>
</welcome-file-list>
</web-app>

redirect.jsp
We have declared welcome-file-list in web.xml as redirect.jsp, So the first request comes to redirect.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<% response.sendRedirect("userRegistration.htm"); %>

disp-servlet.xml
In the web.xml file we have declared 
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="localeResolver"
class="org.springframework.web.servlet.i18n.SessionLocaleResolver">
<property name="defaultLocale" value="en" />
</bean>
<bean id="localeChangeInterceptor"
class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<property name="paramName" value="language" />
</bean>
<bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping" >
<property name="interceptors">
<list>
<ref bean="localeChangeInterceptor" />
</list>
</property>
</bean>
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/" p:suffix=".jsp" />
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"
p:basename="messages" />
<bean id="userValidator" class="com.UserValidator"/>
<bean name="/userRegistration.htm" class="com.UserController"
p:formView="userForm" p:successView="userSuccess"
p:validator-ref="userValidator" />
</beans>
1.SessionLocaleResolver:
Register a “SessionLocaleResolver” bean, named it exactly the same characters “localeResolver“. It resolves the locales by getting the predefined attribute from user’s session.
Note *** If you do not register any “localeResolver”, the default AcceptHeaderLocaleResolver will be used, which resolves the locale by checking the accept-language header in the HTTP request.
2.LocaleChangeInterceptor
Register a “LocaleChangeInterceptor” interceptor and reference it to any handler mapping that need to supports the multiple languages. The “paramName” is the parameter value that’s used to set the locale.
In this case,
userRegistration.htm?language=en – Get the message from English properties file(messages.properties)
userRegistration.htm?language=fr_FR – Get the message from French properties file(messages_fr.properties)
In the ResourceBundleMessageSource, we have given the basename as messages. So the properties file name should be messages.properties

messages.properties
username=User Name
password=Password
gender=Gender
male=Male
female=Female
aboutYou=About You
name.required=User name is required
password.required=Password is required
gender.required=Gender is required
aboutYou.required=About you is required
messages_fr.properties
username=Nom d'utilisateur
password=Mot de passe
gender=Sexe
aboutYou=À propos de vous
male=mâle
female=féminin
name.required=Nom d'utilisateur est nécessaire
password.required=Mot de passe est requis
gender.required=Sexe est requis
aboutYou.required=À propos de vous est requis

As we discussed privious example (Simple Form Validation), I am not going in depth of the Validations and Controllers.
User.java
package com;

public class User {

private String name;
private String password;
private String gender;
private String aboutYou;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getAboutYou() {
return aboutYou;
}
public void setAboutYou(String aboutYou) {
this.aboutYou = aboutYou;
}
}

UserController.java
package com;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

public class UserController extends SimpleFormController {
public UserController() {
setCommandClass(User.class);
setCommandName("user");
}

protected ModelAndView onSubmit(Object command) throws Exception {
User user = (User) command;
return new ModelAndView("userSuccess","user",user);
}
}

UserValidator.java
package com;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
public class UserValidator implements Validator {

public boolean supports(Class arg0) {
return User.class.isAssignableFrom(arg0);
}
public void validate(Object target, Errors errors) {
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "name.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "password.required");
ValidationUtils.rejectIfEmpty(errors, "gender", "gender.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "aboutYou", "aboutYou.required");
User user = (User) target;
}
}

UserForm.jsp
A JSP page, contains two hyperlinks to change the locale manually, and use the spring:message to display the message from the corresponds properties file by checking the current user’s locale.
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<!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=ISO-8859-1">
<title>Registration Page</title>
<style>
.error{
font-style:italic;
color:#ff0000;
}
</style>
</head>
<body>
<form:form method="POST" commandName="user">
<form:errors path="*" cssClass="error"></form:errors><br>
Select your Language : <a href="?language=en">English</a>|<a href="?language=fr_FR">French</a>
<table>
<tr>
<td><spring:message code="username" /></td>
<td><form:input path="name" /></td>
</tr>
<tr>
<td><spring:message code="password" /> :</td>
<td><form:password path="password" /></td>
</tr>
<tr>
<td><spring:message code="gender" /> :</td>
<td><spring:message code="male" /> : <form:radiobutton path="gender" value="M"  /> 
<spring:message code="female" /> : <form:radiobutton path="gender" value="F"  /></td>
</tr>
<tr>
<td><spring:message code="aboutYou" /> :</td>
<td><form:textarea path="aboutYou" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit"></td>
</tr>
</table>
</form:form>
</body>
</html>

default Language is English

If user is not enter any data

If user selects the FRENCH in the userForm





If user is not entered any date

Tuesday, August 3, 2010

Spring Form Validation


In this example you will see how to validate the user registration form that we created in the previous previous example (Spring-Simple Form Controller) To validate the form fields all you need to do is to have a separate UserValidator class that implements the Validator interface, override the validate() method perform all the validations. In the jsp page add form:errors tag to dispaly errors and finally you need to link the UserValidator class with the UserController class. Since the UserControllerclass extends the SimpleFormController class the validate() method will be called automatically. In case you would like to have the error messages in a separate properties file then you need to create a new properties file, add all the error keys and its corresponding values and finally link it to Spring configuration file.
userValidator.java

package com;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
public class UserValidator implements Validator {
public boolean supports(Class arg0) {
return User.class.isAssignableFrom(arg0);
}
public void validate(Object target, Errors errors) {
      ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "name.required"); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "password.required"); ValidationUtils.rejectIfEmpty(errors, "gender", "gender.required"); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "aboutYou", "aboutYou.required");
User user = (User) target;
}
}
Here you need to override the validate method. To check mandatory condition you can use the ValidationUtils class methods like rejectIfEmptyOrWhitespace or rejectIfEmpty. These methods takes three arguments the Errors object, the property name, and the error code. Here we have the error messages in a seperate properties file so we add the error code, you can even add the error messages directly. To do any other validation you have access to the domain object, using the domain object validate the properties, incase there are errors you can use the rejectValue() method of the Errors class to add errors. Here the first argument is the property name and the second argument is the error code.
dispatcher-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/" p:suffix=".jsp" />
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource"
p:basename="messages" />
<bean id="userValidator" class="com.UserValidator"/>
<bean name="/userRegistration.htm" class="com.UserController"
p:formView="userForm" p:successView="userSuccess"
p:validator-ref="userValidator" />
</beans>



messages.properties
In the dispatcher-servlet.xml, we have declared the base name for the ResourceBundleMessageResource as messages, so the property file name should be messages.properties. 
The messages.properties file should be placed in the root of the classpath.

name.required=User name is required
password.required=Password is required
gender.required=Gender is required
aboutYou.required=About you is required

userForm.jsp
Now add the form:errors tags in the jsp page to display the errors.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!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=ISO-8859-1">
<title>Registration Page</title>
<style>
.error{
font-style:italic;
color:#ff0000;
}
</style>
</head>
<body>
<form:form method="POST" commandName="user">
<table>
<tr>
<td>User Name :</td>
<td><form:input path="name" /></td>
<td><form:errors path="name" cssClass="error"/></td>
</tr>
<tr>
<td>Password :</td>
<td><form:password path="password" /></td>
<td><form:errors path="password" cssClass="error"/></td>
</tr>
<tr>
<td>Gender :</td>
<td>Male : <form:radiobutton path="gender" value="M"  /> 
Female : <form:radiobutton path="gender" value="F"  /></td>
<td><form:errors path="gender" cssClass="error"/></td>
</tr>
<tr>
<td>About you :</td>
<td><form:textarea path="aboutYou" /></td>
<td><form:errors path="aboutYou" cssClass="error"/></td>
</tr>
<tr>
<td colspan="2"><input type="submit"></td>
</tr>
</table>
</form:form>

</body>
</html>



The path attribute of the form:errors tag indicate the property for which the error should be displayed. Use path="*" to display all the errors together

<form:form method="POST" commandName="user">
<form:errors path="*" cssClass="error"></form:errors>
<table>
<tr>
<td>User Name :</td>
<td><form:input path="name" /></td>
</tr>
<tr>
<td>Password :</td>
<td><form:password path="password" /></td>
</tr>
<tr>
<td>Gender :</td>
<td>Male : <form:radiobutton path="gender" value="M"  /> 
Female : <form:radiobutton path="gender" value="F"  /></td>
</tr>
<tr>
<td>About you :</td>
<td><form:textarea path="aboutYou" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit"></td>
</tr>
</table>
</form:form>






Spring - Simple Form Controller

index.jsp
When the first request comes to this jsp, its simply redirect to the request to userRegistration.htm

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<% response.sendRedirect("userRegistration.htm"); %>

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>*.htm</url-pattern>
    </servlet-mapping>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>
In the above web.xml file we have declared the url-pattern is *.htm, so it checks any request having *.htm, if any request having *.htm then it checks the corresponding servlet class, In our case its DispatcherServlet. Then Container looks the servlet name declared in web.xml accordingly it invokes the (servlet name in web.xml)-serlvet.xml file. In our case its dispatcher-servlet.xml file


dispatcher-servlet.xml
In the above web.xml file we have declared the servlet name as dispatcher, so our spring config file name should be dispatcher-servlet.xml only

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/" p:suffix=".jsp" />
<bean name="/userRegistration.htm" class="com.UserController"
p:formView="userForm" p:successView="userSuccess" />
</beans>




As you can see, we use "p" namespace here. The "p" namespace is simple and easy to use. Using "p" namespace the properties can be supplied using attributes, rather than elements.
For injecting the simple types we use property name in the "p" namespace and for injecting references we add "-ref" suffix to it. For example we use p:formView for injecting the form view property andp:userService-ref for injecting the user service.
Our request having the /userRegistration.htm, So it invokes the UserContrller. before that it checks the formView, Here it is userForm then it invokes the userForm.jsp first.
userForm.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"



pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!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=ISO-8859-1">
<title>Registration Page</title>
</head>
<body>
<form:form method="POST" commandName="user">
<table>
<tr>
<td>User Name :</td>
<td><form:input path="name" /></td>
</tr>
<tr>
<td>Password :</td>
<td><form:password path="password" /></td>
</tr>
<tr>
<td>Gender :</td>
<td><form:radiobutton path="gender" value="M"  /> 
<form:radiobutton path="gender" value="F"  /></td>
</tr>
<tr>
<td>About you :</td>
<td><form:textarea path="aboutYou" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit"></td>
</tr>
</table>
</form:form>
</body>
</html>
Here the path attribute is used to bind the form fields to the domain object. Here we use the HTTP POST method to submit the form. Inorder to bind the form fields to the domain object successfully the command object should be set to the same name in the jsp page and the controller class. To set the command object name in the jsp page, use the commandName attribute of the form tag.

UserController.java
package com;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

public class UserController extends SimpleFormController {
public UserController() {
setCommandClass(User.class);
setCommandName("user");
}
protected ModelAndView onSubmit(Object command) throws Exception {
User user = (User) command;
return new ModelAndView("userSuccess","user",user);
}
}
Here we extend the UserController from SimpleFormController, this makes the controller class capable of handling forms. Usually a form will be associated with a particular domain object, in our case it is the Userclass. In Spring this domain object is called command object by default. To refer the command object in the jsp page you need to set the command class using the setCommandClass() method in the constructor. Let say the User class has a name property, and to refer this in the jsp page you will use "command.name". You can also change this name by using the setCommandName() method. Here we set the name to user, so to access the user name in the jsp page we use "user.name".
You need to have a method to handle the form when the form is submitted, here the onSubmit()method is used for this purpose. The onSubmit() method has access to the command object, we first typecast the command object to User (our domain object) and then to register the user we call the add() method of the service class and finally return the ModelandView object.
All the forms field values will be submitted as Strings to the form controller. Spring has several pre registered property editors to convert the String values to common data types. Incase you have a custom data type you need to create custom property editors to handle them.
User.java
package com;
public class User {
private String name;
private String password;
private String gender;
private String aboutYou;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getAboutYou() {
return aboutYou;
}
public void setAboutYou(String aboutYou) {
this.aboutYou = aboutYou;
}
}
userSuccess.jsp
we have declared the successView in the dispatcher-servlet.xml as userSuccess, So it invokes the userSuccess.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>Success Page</title>
</head>
<body>
User Details
<hr>
User Name   : ${user.name} <br/>
Gender      : ${user.gender} <br/>
About You   : ${user.aboutYou} <br/>
</body>
</html>