This week, the company leaders hoped that I would come up with an international solution for a project, study for two hours, and use the international support of SpringMVC, and record it here.
Principle: Register localeResolver (area resolver) in DispatchServlet and add Locale interceptor (LocaleChangeInterceptor) to detect changes in the parameters and locale environment in the request.
Register ResourceBundleMessageSource in the application context, defining the path and name of the internationalized file in the program.
1. Language parser
In SpringMVC, commonly used language parsers are
Header resolver: By parsing the accept-language of the client request header information center, we can obtain the international language needed by the user. See =AcceptHeaderLocaleResolver
Cookie resolver: obtains the international information needed by the user by parsing the locale specified by the cookie on the client. See =CookieLocaleResolver
Session resolver: By parsing the loop information in the client request domain, it obtains the required international information and stores it in httpSession. See =SessionLocaleResolver
<bean id="localeResolver"> <property name="defaultLocale" value="en_US" /> </bean>
2. Area Interceptor
We need to register an interceptor for monitoring area changes in the DispatchServlet. It can help us detect request parameters and change the locale according to the language corresponding to the request parameters.
<mvc:interceptors> <bean /> </mvc:interceptors>
3. International resource allocation
<bean id="messageSource"> <property name="defaultEncoding" value="UTF-8" /> <property name="basename" value="classpath*:/ApplicationMessage" /> <property name="useCodeAsDefaultMessage" value="true" /> </bean>
4. Internationalization of the page
Here, I use the jstl's fmt tag to achieve internationalization. Students who are interested can also use the spring message tag.
1) Introduce the tag library <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
2) Specify the international file resource name<fmt:setBundle basename="ApplicationMessage" />
3) Read file information through the key of the international resource file. <fmt:message key="security.account.number" />
5. In the second step we choose is the SessionResolver parser. So in the request, we need to splice locale=specific language identifier after the url parameter (for example: locale=zh_CN).
Note: If you splice the URL on each page, it will be troublesome. Usually users will want to do it. After choosing the language once, they will choose this language first. Therefore, interested students can consider expanding LocaleChangeInterceptor to achieve more complete functions.
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.