Java Internationalization (i18n)
Recently in the function of doing a website internationalization. Use Java for development, using spring+velocity.
Java provides support for i18n, which is integrated by spring and can be easily configured. The main idea is to read the different configuration files according to the language to display the corresponding text. The main steps are as follows:
1. Use the two properties file to save the "symbol" to the corresponding language mapping. such as Messages_en.properties and messages_zh.properties, put them under the classpath of the project.
#messages_en. Propertiestitle=service Introduction
#messages_cn. Properties
title=\u670d\u52a1\u8bf4\u660e
Note Chinese to use Unicode encoding
2. Configure the spring XML file:
Spring offers a variety of international support options, such as browser-based, session, and cookies. How to use cookies in your project
<bean id= "Localeresolver" class= "Org.springframework.web.servlet.i18n.CookieLocaleResolver" > < Property Name= "Cookiemaxage" value= "604800"/> <property name= "Defaultlocale" value= "Zh_cn"/> < Property Name= "CookieName" value= "lang"/> </bean>
resource files in Declaration 1
<bean id= "Messagesource" class= "Org.springframework.context.support.ResourceBundleMessageSource" > < Property Name= "basename" value= "Messages"/> <property name= "Usecodeasdefaultmessage" value= "true"/> </bean>
Use interceptors to process requests to internationalize the corresponding pages
<bean id= "Localechangeinterceptor" class= "Org.springframework.web.servlet.i18n.LocaleChangeInterceptor"/> ... <property name= "interceptors" ref= "Localechangeinterceptor" ></property>
...
Or
<mvc:interceptors><bean class= "Org.springframework.web.servlet.i18n.LocaleChangeInterceptor"/>< Mvc:interceptor>...</mvc:interceptor></mvc:interceptors>
You can then call the placeholder on the VM page.
#springMessage ("title")
3. You can also write a controller to switch languages
@RequestMapping ("/lang") public String Lang ( throws Exception { = Request.getparameter ("Langtype"); if ("en". Equals (Langtype)) { Cookielocaleresolver.setlocale (request, Response, Locale.english); Else { Cookielocaleresolver.setlocale (request, response, Locale.china); } returnnull;}
Java Internationalization (i18n)