Spring Internationalization


 

Spring Internationalization

In this tutorial you will learn how to localize our aplication

In this tutorial you will learn how to localize our aplication

Spring Internationalization

To write an application that supports multiples languages, you need to add the following code in your dispatcher.

1. At first message resources

<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
	<property name="basename" value="/WEB-INF/locale/message" />
	<property name="defaultEncoding" value="UTF-8" />
</bean>

2. Add the LocaleChangeInterceptor as

<mvc:interceptors>
	<bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"
	p:paramName="locale" />
</mvc:interceptors>

3. add the SessionLocaleResolver

<bean id="localeResolver"
	class="org.springframework.web.servlet.i18n.SessionLocaleResolver">
	<property name="defaultLocale" value="en_ES" />
</bean>

4. change the character encoding of your page

<%@ page pageEncoding="UTF-8" contentType="text/html; charset=UTF-8"%>
and include the message tag as
<%@ taglib prefix="message" uri="http://www.springframework.org/tags"%>

5. Replace all labels as

<message:message code="student.roll.no" />

A typical JSP page will look as follows

<%@ page pageEncoding="UTF-8" contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%@ taglib prefix="message" uri="http://www.springframework.org/tags"%>
<html>
<head>
<title>Please Change Language Here</title>
<script type="text/javascript">
function changeLanguage() {
var lang = document.getElementById("locale");
self.location = "load-form?locale=" + lang.value;
}
</script>
</head>
<body>
<br />
<br />
<table align="center" cellpadding="5" cellspacing="5">
<tr>
<td><form:form action="process-form" commandName="sampleForm"
method="POST" enctype="multipart/form-data">
<table align="center">
<tr>
<td><message:message code="student.roll.no" /></td>
<td><form:input path="rollNo" /></td>
</tr>
<tr>
<td><message:message code="student.name" /></td>
<td><form:input path="name" /></td>
</tr>
<tr>
<td><message:message code="student.address" /></td>
<td><form:input path="address" /></td>
</tr>
<tr>
<td align="center" colspan="2"><input type="submit"
value="Process" /></td>
</tr>

</table>
</form:form></td>
<td>
<table>
<form:form action="load-form" method="get" commandName="languageForm">
<tr>
<td><form:select path="locale" onchange="changeLanguage()">
<form:options items="${languages}" itemLabel="langName"
itemValue="value" />
</form:select></td>
</tr>
</form:form>
</table>
</td>
</tr>
</table>
</body>
</html>

When you run this application it will display message as shown below:


Download Source Code

Ads