Internationalization using MessageSource:- In Spring MVC we can show the LocaleResolver to achieve the Internationlization(I18N) to support the multiple language.
WelcomeController.java
package com.manish.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;
public class WelcomeController extends AbstractController{
@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request,
HttpServletResponse response) throws Exception {
ModelAndView model = new ModelAndView("WelcomePage");
return model;
}
}
WelcomePage.jsp
<%@ page contentType="text/html;charset=UTF-8" %>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<html>
<body>
<h1>Spring MVC internationalization example</h1>
Language : <a href="?language=en">English</a>|
<a href="?language=fr">French</a>
<h3>
welcome.springmvc : <spring:message code="welcome.springmvc" text="default text" />
</h3>
Current Locale : ${pageContext.response.locale}
</body>
</html>
app-context.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.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>
<!-- Register the welcome.properties -->
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="welcome" />
</bean>
<!-- Register the bean -->
<bean class="com.manish.controller.WelcomeController" />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
<property name="prefix">
<value>/WEB-INF/pages/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
welcome_fr.properties
welcome.springmvc = Bonjour tout le monde partir du printemps
welcome.properties
welcome.springmvc = Hello world from spring
In above example we can achieve I18N using the two properties file(
welcome_fr.properties,welcome.properties) the welcome.properties can contain the message in english that is default locale and welcome_fr.properties can contain the same message in france language
Output:-
0 Comment(s)