Spring MVC – Code ví dụ Đa ngôn ngữ trong Spring MVC, Internationliaztion-i18n

Spring MVC – Code ví dụ Đa ngôn ngữ trong Spring MVC, Internationliaztion-i18n

Tương tự JSF Framework, Spring MVC cũng hỗ trợ đa ngôn ngữ, giúp hiển thị các loại ngôn ngữ khác nhau mà không cần phải hard code.

Trong ví dụ này mình sẽ thực hiện tạo các file .properties chứa label/text cho từng ngôn ngữ (tiếng anh, tiếng việt, tiếng nhật, tiếng pháp)

Mỗi khi chọn ngôn ngữ nào thì nó sẽ hiển thị label/text của ngôn ngữ đó.

Tạo maven project

Ở ví dụ này mình sử dụng

  • Spring 5.0.2.RELEASE
  • Maven

Code ví dụ Đa ngôn ngữ trong Spring MVC, Internationliaztion-i18n

Thư viện sử dụng:

<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/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>stackjava.com</groupId>
  <artifactId>Springi18n</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>

  <properties>
    <spring.version>5.0.2.RELEASE</spring.version>
  </properties>
  <dependencies>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${spring.version}</version>
    </dependency>
  </dependencies>
</project>

File 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"
  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
  version="2.5">
  <display-name>Springi18n</display-name>
  <servlet>
    <servlet-name>spring-mvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>spring-mvc</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

  <filter>
    <filter-name>encodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>UTF-8</param-value>
    </init-param>
    <init-param>
      <param-name>forceEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>

Đoạn filter dưới đây thực hiện đăng ký CharacterEncodeingFilter của Spring với web.xml (Lưu ý, nó phải filter đầu tiên trong file web.xml)

Việc này giúp hiển thị các ngôn ngữ có encode như tiếng nhật, tiếng hàn…

<filter>
  <filter-name>encodingFilter</filter-name>
  <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
  <init-param>
    <param-name>encoding</param-name>
    <param-value>UTF-8</param-value>
  </init-param>
  <init-param>
    <param-name>forceEncoding</param-name>
    <param-value>true</param-value>
  </init-param>
</filter>
<filter-mapping>
  <filter-name>encodingFilter</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

File spring config:

<?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:context="http://www.springframework.org/schema/context"
  xmlns:mvc="http://www.springframework.org/schema/mvc"
  xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
    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-4.3.xsd">

  <!-- Enables the Spring MVC @Controller programming model -->
  <mvc:annotation-driven />

  <context:component-scan base-package="stackjava.com.springmvchello" />

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

  <bean id="messageSource"
    class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
    <property name="basename" value="/i18n/messages" />
    <property name="defaultEncoding" value="UTF-8" />
  </bean>
  
<!-- 	<bean id="localeResolver"
    class="org.springframework.web.servlet.i18n.SessionLocaleResolver">
 -->
 
  <bean id="localeResolver" 
    class="org.springframework.web.servlet.i18n.CookieLocaleResolver">
    <property name="defaultLocale" value="en" />
    <property name="cookieName" value="myAppLocaleCookie"></property>
    <property name="cookieMaxAge" value="3600"></property>
  </bean>

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

</beans>

Bean messageSource định nghĩa nơi chứa các file message (ví dụ ở đây là ở folder i18n và file có tên bắt đầu là messages)

Bean localeResolver định nghĩa cách xác định ngôn ngữ (Ở đây spring sẽ tạo ra 1 cookies có giá trị là myAppLocaleCookie để xác định ngôn ngữ của client, bạn có thể chuyển sang xác định ngôn ngữ bằng cách sử dụng session. Khi cookies/session hết hạn hoặc bị xóa thì ngôn ngữ sẽ trở về ngôn ngữ mặc định)

mvc:interceptors Thực hiện lọc request có paramName = language để thực hiện đổi ngôn ngữ, ví dụ ?language=vi_VN sẽ chuyển ngôn ngữ sang tiếng việt)

Spring MVC – Code ví dụ Đa ngôn ngữ trong Spring MVC, Internationliaztion-i18n

Các file properties:

hello=Hello
hello=Xin Chào
hello=Bonjour
hello=こんにちは

Controller:

package stackjava.com.springmvchello.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class HomeController {

  @RequestMapping("/")
  public String home() {
    return "home";
  }

}

File hiển thị:

<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<html>
<body>
  <h1>Spring MVC internationalization</h1>

  Language :
  <a href="?language=en">English</a>|
  <a href="?language=vi_VN">Viet Nam</a>|
  <a href="?language=fr_FR">France</a>

  <h2>hello :	<spring:message code="hello" text="default text" /></h2>
  
  Current Locale : ${pageContext.response.locale}

</body>
</html>

Demo

ngôn ngữ mặc đinh – tiếng anh

Code ví dụ Đa ngôn ngữ trong Spring MVC, Internationliaztion-i18n

Ngôn ngữ tiếng việt

Code ví dụ Đa ngôn ngữ trong Spring MVC, Internationliaztion-i18n

Ngôn ngữ tiếng pháp

Code ví dụ Đa ngôn ngữ trong Spring MVC, Internationliaztion-i18n

Ngôn ngữ tiếng nhật:

Code ví dụ Đa ngôn ngữ trong Spring MVC, Internationliaztion-i18n

Spring MVC – Code ví dụ Đa ngôn ngữ trong Spring MVC, Internationliaztion-i18n

Okay, Done!

Download code ví dụ trên tại đây

References:

https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/servlet/i18n/package-summary.html

stackjava.com