This chapter picks up where we left off with the LocaleResolver.

LocalResolver is used to resolve the locale from which the client’s request comes, so that the locale information in the request can be returned in different languages to meet the needs of Spring MVC project internationalization. LocalContextResolver inherits the LocalResolver interface and adds time zone support.

LocalResolver source

First look at LocalResolver default configuration (AcceptHeaderLocaleResolver) source, the configuration realizes LocalResolver interface, and rewrite resolveLocale method, Make it possible to parse the requested locale using the Request Header field:

public class AcceptHeaderLocaleResolver implements LocaleResolver {
    public AcceptHeaderLocaleResolver(a) {}public Locale resolveLocale(HttpServletRequest request) {
        return request.getLocale();
    }

    public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {
        throw new UnsupportedOperationException("Cannot change HTTP accept header - use a different locale resolution strategy"); }}Copy the code

As you can see, the resolveLocale method directly takes the locale field in the request to see which language is most supported on the client side. And the class does not support the set method.

LocalResolver code example

Locale-specific properties file

First, we need to configure three resource files for each language, Create locale_en.properties, locale_en_US. Properties, locale_zh_CN. Note that after you create these three files directly, Intellij will combine them into a single folder (in this case, a folder called locale). The code in the properties file is:

Locale_en.properties file message.locale=en_helloCopy the code
Locale_en_us. properties file message.locale=en_US_helloCopy the code
Locale_zh_CN. Properties file message.locale=zh_CN_helloCopy the code

LocaleResolver configuration in the Spring configuration file

In the root – context configuration LocalResolver bean and configuration corresponding ReloadableResourceBundleMessageSource internationalized resource file, The method gets the resource file for the Locale object you are entering:

<?xml version="1.0" encoding="UTF-8"? >
<beans>

    <context:component-scan base-package="com.test.myapp.example"/>

	<! Rest of the bean configuration -->

    <! - LocaleResolver configuration - >
    <bean id="localeResolver" class="org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver">
    </bean>

    <! -- Internationalization resource file -->
    <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <! "No message found under code" -- Basename value must have a classpath: prefix. -->
    	<! Spring MVC will still find these resource files when it runs -->
        <property name="basename" value="classpath:locales/locale" />
        <! If no code is found in the internationalized resource file, return this code as the name.
        <! --<property name="useCodeAsDefaultMessage" value="true" />-->
        <! --<property name="defaultEncoding" value="ISO-8859-1"/>-->
    </bean>

	<! Rest of the bean configuration -->

</beans>
Copy the code

LocaleResolver Test interface

The next step is to configure an interface for our LocaleResolver to get information about which languages are supported by the current client and which languages are preferred, and then get information from the corresponding properties file.

@Controller
public class LocaleResolverController {
    @RequestMapping(value="/accept-header-resolver.do", method = RequestMethod.GET)
    public ModelAndView resolveLocale(HttpServletRequest request) {
        String clientLocale = "";
        // Get the language supported by the client
        Enumeration<Locale> locales = request.getLocales();
        while (locales.hasMoreElements()) {
            Locale locale = locales.nextElement();
            clientLocale += locale + ",";
        }
        RequestContext requestContext = new RequestContext(request);
        // Get information from properties for the corresponding locale
        String value = requestContext.getMessage("message.locale");

        ModelAndView modelAndView = new ModelAndView("localeResolver");

        modelAndView.addObject("clientLocale", clientLocale);
        modelAndView.addObject("currentLocale", requestContext.getLocale());
        modelAndView.addObject("localeResource", value);
        returnmodelAndView; }}Copy the code

In the preceding code, clientLocale represents the language supported by the client browser, currentLocale is the preferred language of the client, and value represents the field value in the corresponding language Properties retrieved based on the preferred language of the client.

LocaleResolver test front end page

The above test interface returns a ModelAndView object, so we also need the JSP front-end file to output the above fields:

<%@ page contentType="text/html; Charset =UTF-8" language=" Java "%> < HTML > <head> <title>locale resolver page</title> </head> <body> <p> ${clientLocale} currentLocale of the client: ${currentLocale}, server: ${localeResource} </p> </body> </ HTML >Copy the code

Now that we have finished writing the specific code, let’s move on to testing.

test

This test uses Chrome as an example. First check out the Chrome Settings section:

! [chrome language Settings] (/ Users/shenruofan 4.32.43 / Desktop/screen shot 2018-11-06 afternoon. PNG)

As you can see, in the language Settings section we set the preferred language to English (EN). Run the project, in the browser input: http://localhost:8080/accept-header-resolver.do, we will see the following identification:

The client can be en, en, en_US, and zh_CN. The current region of the client is EN, and the corresponding content of the server is en_helloCopy the code

After that, we put Chinese (simplified) (zh_CN) as the first language preference in the language Settings, and then enter the same address, the following flag will appear:

The client can be zh_CN, en,en_US. The region of the client is zh_CN, and the corresponding content of the server is zh_CN_helloCopy the code

This can indicate that our LocaleResolver has been in effect in the project.