Spring MVC Getting Started Guide (8): Internationalization

    How to internationalize other content of our website (such as menu, title, etc.)? This is the content of this article -> Internationalization.

        The so-called internationalization is to support multiple languages, web applications can display different languages ​​in different browsing environments, such as Chinese, English and so on.


1. The content added to the springservlet-config.xml file for configuring our project is as follows:

    <!-- store locale information
     The SessionLocaleResolver class stores localization information in sessions with a predefined session name
     Judging user language defaultLocale from session: default language -->
    <bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver">
        <property name="defaultLocale" value="zh_CN" />
    </bean>

    <!-- Internationalized resource file
    1.messageSource configures the path of the internationalized resource file,
    2.classpath:messages refers to the messages_zh_CN.properties file and the messages_en_US.properties file under the classpath path
    3. Set "useCodeAsDefaultMessage", the default is false, so that when Spring cannot find the messageKey in the ResourceBundle, it will throw NoSuchMessageException, if it is set to True, it will not throw an exception, but use the messageKey as the return value. -->
    <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <property name="defaultEncoding" value="UTF-8" />
        <property name="useCodeAsDefaultMessage" value="true" />
        <property name="basenames" >
            <list>
                <value>classpath:messages</value>
            </list>
        </property>
    </bean>
    <!--The interceptor intercepts the HTTP request through the parameter named "lang", so that it resets the regionalization information of the page-->
    <mvc:interceptors>
        <bean id="localeChangeInterceptor" class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
            <property name="paramName" value="lang" />
        </bean>
    </mvc:interceptors>


2. Add the contents of GlobalController.java to the com.ray.controllers package as follows:

/**
 * @author Ray
 * @date 2018/4/20 0020
 * Internationalization support
 */
@Controller
@RequestMapping(value = "/global")
public class GlobalController {

    @RequestMapping(value = "/test", method = {RequestMethod.GET})
    public String test(HttpServletRequest request, Model model, @RequestParam(value = "langType", defaultValue = "zh") String langType) {

        if (!model.containsAttribute("contentModel")) {

            if (langType.equals("zh")) {
                Locale locale = new Locale("zh", "CN");
                request.getSession().setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME, locale);
            } else if (langType.equals("en")) {
                Locale locale = new Locale("en", "US");
                request.getSession().setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME, locale);
            } else {
                request.getSession().setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME, LocaleContextHolder.getLocale());
            }
            //Get internationalization information from background code
            RequestContext requestContext = new RequestContext(request);
            model.addAttribute("money", requestContext.getMessage("money"));
            model.addAttribute("date", requestContext.getMessage("date"));


            FormatModel formatModel = new FormatModel();

            formatModel.setMoney(12345.678);
            formatModel.setDate(new Date());

            model.addAttribute("contentModel", formatModel);
        }
        return "globaltest";
    }

}


3. Add two files, messages_zh.properties and messages_en.properties, to the source folder resources in the project

messages_zh.properties

money=\u91D1\u94B1
date=\u65E5\u671F

messages_en.properties

money=Money
date=Date


4. Add the globaltest.jsp view in the views folder, the content is as follows:

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" %>
<%@taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
    <base href="<%=basePath%>">
    <title>Insert title here</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
</head>

<body>

<a href="global/test?langType=zh">中文</a> | <a href="global/test?langType=en">英文</a><br/>

    <h3>The following shows the internationalization information obtained in the background:</h3>
    ${money}<br/>
    ${date}<br/><br/>

    <h3>The following shows the internationalization information bound directly in the view:</h3>
    <spring:message code="money"/>:<br/>
    <spring:eval expression="contentModel.money"></spring:eval><br/><br/>
    <spring:message code="date"/>:<br/>
    <spring:eval expression="contentModel.date"></spring:eval><br/>
</body>
</html>


Run the test:



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325393229&siteId=291194637