目录
2:让Spring的ResourceBundleMessageSource管理国际化资源文件
2:使用系统的区域信息拦截器进行设置(LocaleChangeInterceptor)
一:简单国际化
0:导包,防止jstl和fmt不能使用
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency><dependency>
<groupId>org.apache.taglibs</groupId>
<artifactId>taglibs-standard</artifactId>
<version>1.2.5</version>
</dependency>
1:写好国际化资源文件--一定放在资源目录下
2:让Spring的ResourceBundleMessageSource管理国际化资源文件
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"> <property name="basename" value="message"></property> </bean>
3、直接去页面取值
4、现象:是按照浏览器带来语言信息决定;
Locale locale = request.getLocale();//获取到浏览器的区域信息
系统默认是这样获取系统语言信息;
二:点击链接进行资源国际化
1:自定义区域语言解析器-LocalResolver
package com.wkl;
import org.springframework.web.servlet.LocaleResolver;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;
/**
* Description:自定义区域解析器
* Date: 2020/8/18 - 下午 1:56
* author: wangkanglu
* version: V1.0
*/
public class MyLocalResolver implements LocaleResolver {
@Override
public Locale resolveLocale(HttpServletRequest request) {
String lang = request.getParameter("lang");
Locale l = null;
if(!"".equals(lang) && lang!=null){
l = new Locale(lang.split("_")[0],lang.split("_")[1]);
}else {
l = request.getLocale();
}
return l;
}
@Override
public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {
}
}
2:配置自定义解析器
在初始化语言解析器时,会从容器中找id为localeResolver的解析器;没有采用默认的;所以我们自定义的id就设置成localeResolver
<!--自定义区域解析器--> <bean id="localeResolver" class="com.wkl.MyLocalResolver"></bean>
三:点击链接使用SessionLocaleResolver
1:在请求的时候设置在session中
package com.wkl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;
import javax.servlet.http.HttpSession;
import java.util.Locale;
/**
* Description:
* Date: 2020/8/18 - 上午 10:18
* author: wangkanglu
* version: V1.0
*/
@Controller
public class LoginPageController {
@Autowired
private MessageSource messageSource;
@RequestMapping("tologinpage")
public String toLoginPage(String lang, Locale locale, HttpSession session){
Locale l = null;
if(!"".equals(lang) && lang!=null){
l = new Locale(lang.split("_")[0],lang.split("_")[1]);
}else {
l = locale;
}
session.setAttribute(SessionLocaleResolver.class.getName() + ".LOCALE",l);
return "login";
}
}
2:使用系统的区域信息拦截器进行设置(LocaleChangeInterceptor)
所以:
<a href="/tologinpage?locale=zh_CN">中文</a> <a href="/tologinpage?locale=en_US">英文</a>
在dispatcher-servlet.xml中配置
<!--区域信息从session中拿--> <bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver"></bean> <!--配置区域信息拦截器--> <mvc:interceptors> <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"></bean> </mvc:interceptors>