14. Spring MVC region information (LocaleResolver)

Table of Contents


1. Basic introduction to Spring MVC

2. Spring MVC basic operation configuration and operation process

3. Spring MVC view resolver

4. Spring MVC front-end and back-end data interaction (Controller, RequestMapping, RequestBody, RequestParam, ModelAndView, etc.)

5. Spring ResponseEntity object details and source code analysis

6. Spring MVC RESTful style

7. HTTP request method and HTTP request status code

8. Spring server-side data validation (JSR-303)

9. Spring file upload and download (MultipartFile object)

10. What are the characteristics of HttpClient, RestTemplate, OkHttp? Detailed use of RestTemplate request template

11. Spring MVC interceptor usage

12. Spring MVC unified exception handling

13. Overview of the nine components of Spring MVC

14. Spring MVC locale information (LocaleResolver)

15. Spring MVC theme (ThemeSource)


Spring MVC region information (LocaleResolver)

  • Table of contents
  • area information
  • Get region information
    • 1.Accept request header parser
    • 2. Cookie parser
    • 3. Session parser
  • Region change interceptor

Region information

Many layers of Spring’s architecture provide support for internationalization, as does the Spring MVC framework. DispatcherServlet provides the ability to automatically use the user’s locale information to resolve messages. And this is done by LocaleResolver object

When a request comes in for processing, the DispatcherServlet looks for a locale resolver. If found, try to use it to set locale-related information. The region information parsed by the region resolver can be obtained by calling RequestContext.getLocale(). In addition, if you need to automatically parse the region information, you can add an interceptor before the processor mapping, and use it to change the region information according to different conditions or environments, for example, according to a parameter value in the request

In order for a web application to support internationalization, it must identify each user’s preferred locale and display content according to that locale.
In a Spring MVC application, the user’s locale is identified through a locale resolver, which must implement the LocaleResolver interface. Spring MVC provides several LocaleResolver implementations, which can resolve regions according to different conditions. In addition, you can also implement this interface to create your own zone resolver

To define a locale resolver, just register a Bean of type LocaleResolver in the web application context. The bean name of the locale resolver must be set to localeResolver so that the DispatcherServlet can detect it automatically

Note: DispatcherServlet can only register one zone resolver.

Get region information

In addition to getting the client’s region information, sometimes their time zone information is also very useful. The LocaleContextResolver interface provides an extension point for LocaleResolver, allowing the resolver to provide more information in the LocaleContext, which can include time zone information

If the user’s time zone information can be parsed, it can be obtained through the RequestContext.getTimeZone() method. The time zone information will be automatically used by the date/time converter Converter and the formatting object Formatter registered under SpringConversionService

1.Accept request header parser

The AcceptHeaderLocaleResolver parser will check whether the request sent by the client (for example, browser, etc.) carries the accept-language request header. Usually, the request header field contains the region information of the client operating system
Note: This parser does not support the parsing of time zone information

The default locale resolver used by Spring is AcceptHeaderLocaleResolver. The locale is resolved by examining the accept-language header of the HTTP request. This header is set by the user’s web browser according to the locale of the underlying operating system
Note: This locale resolver cannot change the user’s locale because it cannot modify the locale of the user’s operating system

2. Cookie parser

The CookieLocaleResolver analysis will check whether the client has a cookie, which may store the Locale or TimeZone information of the region. If appropriate values are found, the parser uses them. Through the properties of the parser, you can specify the name of the cookie and its maximum lifetime

Use CookieLocaleResolver to resolve the locale. If the cookie does not exist, it will determine the default locale based on the accept-language HTTP header

How to define a CookieLocaleResolver

<bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver">
    <property name="cookieName" value="clientlanguage"/>
    <!-- The unit is seconds. If set to -1, the cookie will not be persisted (it will be deleted after the client closes the browser) -->
    <property name="cookieMaxAge" value="100000">
</bean>

Attributes supported by CookieLocaleResolver

Attribute Default Value Description
cookieName classname + LOCALE cookie name
cookieMaxAge Integer.MAX_INT The maximum time the cookie is kept on the client. If the value is -1, the cookie will not be persisted and will become invalid after the client browser is closed
cookiePath / restricts the cookie to only be visible to certain paths under the site. If cookiePath is specified, the cookie will only be visible to all sites under this path and its subpaths

3.Session parser

SessionLocaleResolver allows to get the Locale and TimeZone information that may be associated with the user request from the session. Different from CookieLocaleResolver, this access strategy only accesses the relevant regional information in the HttpSession of the Servlet container to the local. Therefore, these settings will only be temporarily saved for the session (session), after the session ends, these settings will become invalid

Note: This parser is not directly related to other external session management mechanisms, such as Spring’s Session project. The SessionLocaleResolver simply extracts the corresponding attributes from the HttpSession object related to the current request HttpServletRequest, and modifies its value, nothing more

Another way to resolve locales is through SessionLocaleResolver. It resolves the locale by examining the properties preset in the user session. If this session attribute is absent, it will determine the default locale based on the accept-language HTTP header.

<bean id="localeResolver" class="org.springframewrok.web.servlet.i18n.SessionLocaleResolver">
    <property name="defaultLocale" value="en"/>
</bean>

If the session attribute does not exist, the defaultLocale attribute can be set for this resolver. Note that this locale resolver can change the user’s locale by modifying the session attribute holding the locale

Region change blocker

You can add a LocaleChangeInterceptor interceptor before the handler mapping to change locale information. It detects the parameter in the request and updates the locale accordingly based on its value. It changes the locale by calling the LocaleResolver’s setLocale() method.

The following code configuration shows how to change the locale for all resource requests that request the *.view path and carry the siteLanguage parameter

For example, a request to the URL http://www.test.com/home.view?siteLanguage=nl will change the site language to Dutch

<bean id="localeChangeInterceptor" class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
    <property name="paramName" value="siteLanguage"/>
</bean>

<bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver"/>

<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
    <property name="interceptors">
        <list>
            <ref bean="localeChangeInterceptor"/>
        </list>
    </property>
    <property name="mappings">
        <value>/**/*.view=someController</value>
    </property>
</bean>