• Java
    • JAXB Tutorial
      • What is JAXB
      • JAXB Marshalling Example
      • JAXB UnMarshalling Example
  • Spring Tutorial
    • Spring Core Tutorial
    • Spring MVC Tutorial
      • Quick Start
        • Flow Diagram
        • Hello World Example
        • Form Handling Example
      • Handler Mapping
        • BeanNameUrlHandlerMapping
        • ControllerClassNameHandlerMapping
        • SimpleUrlHandlerMapping
      • Validation & Exception Handling
        • Validation+Annotations
        • Validation+ResourceBundle
        • @ExceptionHandler
        • @ControllerAdvice
        • Custom Exception Handling
      • Form Tag Library
        • Textbox Example
        • TextArea Example
        • Password Example
        • Dropdown Box Example
        • Checkboxes Example
        • Radiobuttons Example
        • HiddenValue Example
      • Misc
        • Change Config file name
    • Spring Boot Tutorial
  • Hibernate Tutorial
  • REST Tutorial
    • JAX-RS REST @PathParam Example
    • JAX-RS REST @QueryParam Example
    • JAX-RS REST @DefaultValue Example
    • JAX-RS REST @Context Example
    • JAX-RS REST @MatrixParam Example
    • JAX-RS REST @FormParam Example
    • JAX-RS REST @Produces Example
    • JAX-RS REST @Consumes Example
    • JAX-RS REST @Produces both XML and JSON Example
    • JAX-RS REST @Consumes both XML and JSON Example
  • Miscellaneous
    • JSON Parser
      • Read a JSON file
      • Write JSON object to File
      • Read / Write JSON using GSON
      • Java Object to JSON using JAXB
    • CSV Parser
      • Read / Write CSV file
      • Read/Parse/Write CSV File – OpenCSV
      • Export data into a CSV File
      • CsvToBean and BeanToCsv – OpenCSV

JavaInterviewPoint

Java Development Tutorials

Spring MVC Internationalization i18n Example | SessionLocaleResolver

November 5, 2018 by javainterviewpoint Leave a Comment

Spring Framework is bundled with LocaleResolver which enables the support for Internationalization (i18n) and Localization  (L10n). In this Spring MVC Internationalization i18n Example, lets add the Internationalization support to our Spring MVC Hello World application.

We will be creating a simple Spring MVC application which displays the page contents in English, German and Italian languages.

Folder Structure:

Spring MVC Internationalization i18n Example

  1. Create a simple Maven webapp Project “SpringMVCInternationalization” and create a package for our source files “com.javainterviewpoint” under  src/main/java 
  2. Now add the following dependency in the POM.xml
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    	<modelVersion>4.0.0</modelVersion>
    	<groupId>com.javainterviewpoint</groupId>
    	<artifactId>SpringMVCInternationalization</artifactId>
    	<packaging>war</packaging>
    	<version>0.0.1-SNAPSHOT</version>
    	<name>SpringMVCInternationalization Maven Webapp</name>
    	<url>http://maven.apache.org</url>
    
    	<properties>
    		<jdk.version>1.8</jdk.version>
    		<spring.version>4.3.7.RELEASE</spring.version>
    		<jstl.version>1.2</jstl.version>
    		<servlet.version>3.1.0</servlet.version>
    		<commons.fileupload.version>1.3.2</commons.fileupload.version>
    	</properties>
    
    	<dependencies>
    		<!-- Spring Dependency -->
    		<dependency>
    			<groupId>org.springframework</groupId>
    			<artifactId>spring-webmvc</artifactId>
    			<version>${spring.version}</version>
    		</dependency>
    
    		<dependency>
    			<groupId>org.springframework</groupId>
    			<artifactId>spring-context</artifactId>
    			<version>${spring.version}</version>
    		</dependency>
    
    		<!-- JSTL Dependency -->
    		<dependency>
    			<groupId>jstl</groupId>
    			<artifactId>jstl</artifactId>
    			<version>${jstl.version}</version>
    		</dependency>
    
    		<!-- Servlet Dependency -->
    		<dependency>
    			<groupId>javax.servlet</groupId>
    			<artifactId>javax.servlet-api</artifactId>
    			<version>${servlet.version}</version>
    			<scope>provided</scope>
    		</dependency>
    	</dependencies>
    	<build>
    		<finalName>SpringMVCInternationalization</finalName>
    		<plugins>
    			<plugin>
    				<groupId>org.apache.maven.plugins</groupId>
    				<artifactId>maven-compiler-plugin</artifactId>
    				<version>3.3</version>
    				<configuration>
    					<source>${jdk.version}</source>
    					<target>${jdk.version}</target>
    				</configuration>
    			</plugin>
    		</plugins>
    	</build>
    </project>
    
  3. Create the Java class HelloController.java under  com.javainterviewpoint folder.
  4. Place the messages_en.properties, messages_de.properties and messages_it.properties under src/main/resources folder
  5. Place the welcome.jsp under the sub directory under WEB-INF/Jsp

Other interesting articles which you may like …

  • Spring MVC Multiple File Upload Example
  • Spring MVC 5 Thymeleaf 3 Hello World Example
  • Spring MVC CRUD Example with MySql + JdbcTemplate
  • AngularJS Spring MVC CRUD – $http service
  • AngularJS Spring MVC integration
  • Spring MVC Form Validation -Annotations and ResourceBundle
  • Spring MVC Exception Handling @ExceptionHandler
  • Spring MVC Exception Handling @ControllerAdvice and @ExceptionHandler
  • Spring MVC Custom Exception Handling
  • context:annotation-config vs context:component-scan
  • Spring MVC BeanNameUrlHandlerMapping Example
  • Spring MVC ControllerClassNameHandlerMapping Example
  • Spring MVC SimpleUrlHandlerMapping Example
  • Spring MVC Flow Diagram
  • Spring MVC Multiple submit buttons in a single form
  • Spring MVC SimpleFormController Example
  • Spring 4 – Spring MVC Hello World Example
  • Spring REST Hello World Example – JSON and XML responses
  • ClassNotFoundException: org.springframework.web.context.ContextLoaderListener
  • Fix missing src/main/java folder in Eclipse Maven Project – 2 build path entries are missing

Spring MVC Internationalization i18n Example

Dependency Tree

[INFO] ------------------------------------------------------------------------
[INFO] Building SpringMVCInternationalization Maven Webapp 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO] 
[INFO] --- maven-dependency-plugin:2.1:tree (default-cli) @ SpringMVCInternationalization ---
[INFO] com.javainterviewpoint:SpringMVCInternationalization:war:0.0.1-SNAPSHOT
[INFO] +- org.springframework:spring-webmvc:jar:4.3.7.RELEASE:compile
[INFO] |  +- org.springframework:spring-aop:jar:4.3.7.RELEASE:compile
[INFO] |  +- org.springframework:spring-beans:jar:4.3.7.RELEASE:compile
[INFO] |  +- org.springframework:spring-core:jar:4.3.7.RELEASE:compile
[INFO] |  |  \- commons-logging:commons-logging:jar:1.2:compile
[INFO] |  +- org.springframework:spring-expression:jar:4.3.7.RELEASE:compile
[INFO] |  \- org.springframework:spring-web:jar:4.3.7.RELEASE:compile
[INFO] +- org.springframework:spring-context:jar:4.3.7.RELEASE:compile
[INFO] +- jstl:jstl:jar:1.2:compile
[INFO] \- javax.servlet:javax.servlet-api:jar:3.1.0:provided
[INFO] ------------------------------------------------------------------------

Spring Configuration File –  SpringConfig-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"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc.xsd">

	<context:component-scan base-package="com.javainterviewpoint"> </context:component-scan>
	<mvc:annotation-driven> </mvc:annotation-driven>

	<bean id="messageSource"
		class="org.springframework.context.support.ResourceBundleMessageSource">
		<property name="basename" value="messages" />
	</bean>
	
	<bean id="localeResolver"
		class="org.springframework.web.servlet.i18n.SessionLocaleResolver">
		<property name="defaultLocale" value="en" />
	</bean>

	<mvc:interceptors>
		<bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
			<property name="paramName" value="lang" />
		</bean>
	</mvc:interceptors>

	<bean id="viewResolver"
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix">
			<value>/WEB-INF/Jsp/</value>
		</property>
		<property name="suffix">
			<value>.jsp</value>
		</property>
	</bean>

</beans>
  • <context:component-scan> will let the Spring Container to search for all the annotation under the package “com.javainteriviewpoint”. 
  • <mvc:annotation-driven/> annotation will activate the @Controller, @RequestMapping, @Valid etc annotations.
  • ResourceBundleMessageSource is one of the Spring Message source entity which implements the MessageSource interface, it will be used to read the “message_*.properties” files present in the classpath. We will be passing the name of the property file to the “basename” property.
<bean id="messageSource"
  class="org.springframework.context.support.ResourceBundleMessageSource">
	<property name="basename" value="messages" />
</bean>
  • We can get the Current locale of the user by different locale resolution strategy such as Accept-Language which is present in the header, session, cookie. All the resolvers provided by Spring will be implementing the LocaleResolver.
  • We have used SessionLocaleResolver in our case to use the locale for the particular session and we have set the defaultLocale to English.
<bean id="localeResolver"
  class="org.springframework.web.servlet.i18n.SessionLocaleResolver">
	<property name="defaultLocale" value="en" />
</bean>
  • Note: The bean id has to be “localeResolver”,  if not Spring will try to register the default resolver AcceptHeaderLocaleResolver
  • LocaleChangeInterceptor is a special interceptor in Spring which enables you to change the locale based on the parameter which is present in the request. In our case it is “lang”, using which the user can change the change a different language.
<mvc:interceptors>
  <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
     <property name="paramName" value="lang" />
  </bean>
</mvc:interceptors>
  • The view is resolved through “InternalResourceViewResolver” which searches for the jsp files under the /WEB-INF/Jsp/ directory.
<bean id="viewResolver"
  class="org.springframework.web.servlet.view.InternalResourceViewResolver">
	<property name="prefix">
		<value>/WEB-INF/Jsp/</value>
	</property>
	<property name="suffix">
		<value>.jsp</value>
	</property>
</bean>

locale specific message resources

Our application supports 3 languages English, German and Italian. Add the messages in each languges to the corresponding property file.

messages_en.properties

spring.welcome = Welcome to Javainterviewpoint
spring.content = Spring MVC Internationalization (i18n) and Localization (L10n) Example

messages_de.properties

spring.welcome = Willkommen bei Javainterviewpoint
spring.content = Spring MVC Internationalisierung (i18n) und Lokalisierung (L10n) Beispiel

messages_it.properties

spring.welcome = Benvenuti in Javainterviewpoint
spring.content =  Esempio di Spring MVC Internationalization (i18n) e Localization (L10n)

web.xml

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
    version="3.1">

    <servlet>
        <servlet-name>SpringConfig</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
         <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value></param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>SpringConfig</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    
     <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/SpringConfig-servlet.xml</param-value>
    </context-param>
	
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
</web-app>

The web.xml has everything about the application that a server needs to know, which is placed under the WEB-INF directory.  It contains the name of the SpringConfiguration file, when the DispatcherServlet is initialized the framework will try to load a configuration file “[servlet-name]-servlet.xml” under the WEB-INF directory.

HelloController.java

package com.javainterviewpoint;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class HelloController
{
    @GetMapping("/hello")
    public ModelAndView welcome()
    {
        return new ModelAndView("welcome");
    }
}
  • We have annotated our “HelloController” class with @Controller annotation which tells Spring Container to treat this class as a Controller.
  • @GetMapping annotation on top of welcome() redirects the request to this method, when the request given is “/hello” and it can take only GET request and redirects the user to the welcome.jsp

welcome.jsp

The welcome.jsp should be created under /WEB-INF/Jsp folder.

<%@ page contentType="text/html;charset=UTF-8"%>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<html>
<body>
	<h1>Spring MVC Internationalization i18n Example</h1>

	Select Language : <a href="?lang=en">English</a> | <a href="?lang=de">German</a> | <a href="?lang=it">Italian</a>

	<h2>
		<spring:message code="spring.welcome" />
	</h2>
	<h3>
		<spring:message code="spring.content" />
	</h3>

</body>
</html>

The <spring:message> tag provides the internationalization support, the code attribute act as a key while looking up for the messages in the property file.

Output

Hit on the URL : http://localhost:8080/SpringMVCInternationalization/hello

Since we have provided the defaultLocale as English the page will load its content in English

Spring MVC Internationalization i18n Example 1

Hit on the URL http://localhost:8080/SpringMVCInternationalization/hello?lang=de , alternatively click on the German Hyperlink to make the page load it contents in German

Spring MVC Internationalization i18n Example 2

Hit on the URL http://localhost:8080/SpringMVCInternationalization/hello?lang=it to load the contents in italian

Spring MVC Internationalization i18n Example 3

Filed Under: Java, Spring, Spring MVC Tagged With: i18n, L10n, Localization, SessionLocaleResolver, Spring MVC Internationalization, Spring MVC Internationalization i18n

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Java Basics

  • JVM Architecture
  • Object in Java
  • Class in Java
  • How to Set Classpath for Java in Windows
  • Components of JDK
  • Decompiling a class file
  • Use of Class.forName in java
  • Use Class.forName in SQL JDBC

Oops Concepts

  • Inheritance in Java
  • Types of Inheritance in Java
  • Single Inheritance in Java
  • Multiple Inheritance in Java
  • Multilevel Inheritance in Java
  • Hierarchical Inheritance in Java
  • Hybrid Inheritance in Java
  • Polymorphism in Java – Method Overloading and Overriding
  • Types of Polymorphism in java
  • Method Overriding in Java
  • Can we Overload static methods in Java
  • Can we Override static methods in Java
  • Java Constructor Overloading
  • Java Method Overloading Example
  • Encapsulation in Java with Example
  • Constructor in Java
  • Constructor in an Interface?
  • Parameterized Constructor in Java
  • Constructor Chaining with example
  • What is the use of a Private Constructors in Java
  • Interface in Java
  • What is Marker Interface
  • Abstract Class in Java

Java Keywords

  • Java this keyword
  • Java super keyword
  • Final Keyword in Java
  • static Keyword in Java
  • Static Import
  • Transient Keyword

Miscellaneous

  • newInstance() method
  • How does Hashmap works internally in Java
  • Java Ternary operator
  • How System.out.println() really work?
  • Autoboxing and Unboxing Examples
  • Serialization and Deserialization in Java with Example
  • Generate SerialVersionUID in Java
  • How to make a class Immutable in Java
  • Differences betwen HashMap and Hashtable
  • Difference between Enumeration and Iterator ?
  • Difference between fail-fast and fail-safe Iterator
  • Difference Between Interface and Abstract Class in Java
  • Difference between equals() and ==
  • Sort Objects in a ArrayList using Java Comparable Interface
  • Sort Objects in a ArrayList using Java Comparator

Follow

  • Coding Utils

Useful Links

  • Spring 4.1.x Documentation
  • Spring 3.2.x Documentation
  • Spring 2.5.x Documentation
  • Java 6 API
  • Java 7 API
  • Java 8 API
  • Java EE 5 Tutorial
  • Java EE 6 Tutorial
  • Java EE 7 Tutorial
  • Maven Repository
  • Hibernate ORM

About JavaInterviewPoint

javainterviewpoint.com is a tech blog dedicated to all Java/J2EE developers and Web Developers. We publish useful tutorials on Java, J2EE and all latest frameworks.

All examples and tutorials posted here are very well tested in our development environment.

Connect with us on Facebook | Privacy Policy | Sitemap

Copyright ©2023 · Java Interview Point - All Rights Are Reserved ·