SpringMVC国际化
目录:
1、SpringMVC国际化流程:
2、localeResolver作用:
3、基于session的国际化实现:
4、测试源代码:
5、SpringMVC配置文件:
1、SpringMVC国际化流程:
答:(1)在SpringMVC配置文件application-mvc.xml下配置资源绑定:<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<!-- 国际化信息所在的文件名 -->
<property name="basename" value="messages" />
<!-- 如果在国际化资源文件中找不到对应代码的信息,就用这个代码作为名称 -->
<property name="useCodeAsDefaultMessage" value="true" />
</bean>
(2)将messages文件放到classpath中。
(3)页面中引入spring标签:<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<spring:message code="login" arguments="x,y" argumentSeparator=","/>
arguments是用来给资源文件添加参数的,
argumentSeparator是用来分割多个参数的标记
默认是基于浏览器请求的国际化实现
2、localeResolver作用:
答:在SpringMVC中,用户的区域是通过区域解析器来识别的,它必须实现LocaleResolver接口,SpringMVC提供了几个LocaleResolver实现,使得可以按照不同的条件来解析。
要定义一个区域解析器,只需在web应用程序上下文中注册一个LocaleResolver类型的Bean就可以了。首先必须将区域解析器的Bean名称设置为localeResolver,这样DispatcherServlet才能自动侦测到它。注意,每个DispatcherServlet只能注册一个区域解析器。
答:在SpringMVC的配置文件中加入如下代码:
<mvc:interceptors>
<!-- 国际化操作拦截器 如果采用基于(请求/Session/Cookie)则必需配置 -->
<bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" />
<!-- 全局的拦截器 -->
<bean class="com.remoa.user.action.LogHandlerInterceptor"></bean>
<!-- 局部拦截器 -->
<mvc:interceptor>
<mvc:mapping path="/user/*" />
<bean class="com.remoa.user.action.AuthHandlerInterceptor">
<property name="allowURIs">
<list>
<value>/login.action</value>
<value>/toRegister.action</value>
<value>/doregister.action</value>
<value>/checklogin.action</value>
<value>/lang.action</value>
</list>
</property>
</bean>
</mvc:interceptor>
</mvc:interceptors>
<bean id="localeResolver"
class="org.springframework.web.servlet.i18n.SessionLocaleResolver">
<property name="defaultLocale" value="zh_CN"></property>
</bean>
从页面传入参数,在action中改变编码
Locale locale = new Locale("zh", "CN");
request.getSession().setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME,locale);
4、测试源代码:
答:说明:本示例代码是建立在上一篇《SpringMVC文件上传、数据校验》的基础上的,只展示增加代码。
(1)控制层UserAction.java添加如下方法:
@RequestMapping(value="/lang.action", method=RequestMethod.GET)
public String LoginLang(String locale,HttpSession session){
Locale lo = null;
if("zh".equals(locale)){
lo = new Locale("zh", "CN");
}else{
lo = new Locale("en", "US");
}
session.setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME, lo);
return "user/login";
}
(2)加入两个配置文件messages_en_US.properties和messages_en_CN.properties
图4.1 messages_en_US.properties文件内容
图4.2 messages_en_CN.properties文件内容
(3)测试页面login.jsp<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script type="text/javascript" src="${path }/bootstrap/js/jquery.min.js" ></script>
<script type="text/javascript" src="${path }/bootstrap/js/bootstrap.min.js" ></script>
<link rel="stylesheet" href="${path }/bootstrap/css/bootstrap.min.css" />
<title><spring:message code="userLogin"></spring:message></title>
<style>
body {
font-family: "Helvetica Neue", Helvetica, Arial, "Microsoft Yahei UI", "Microsoft YaHei", SimHei, "\5B8B\4F53", simsun, sans-serif;
}
.error{
color:red;
}
</style>
</head>
<body>
<div class="container">
<div class="col-md-12 text-right">
<a href="${path }/user/lang.action?locale=zh">中文 </a>|
<a href="${path }/user/lang.action?locale=en">English</a>
</div>
<div class="col-md-7" style="text-align:center; font-size:25px">
<spring:message code="userLogin"></spring:message>
</div>
<div class="col-md-6">
<form class="form" action="checklogin.action" method="post" enctype="multipart/form-data" role="form" >
<div class="form-group col-md-12">
<label for="account" class="col-md-3 control-label">
<spring:message code="account"></spring:message>
</label>
<div class="col-md-9 col-md-12">
<input type="text" name="account" class="form-control" placeholder='<spring:message code="accountInstruction"></spring:message>' />
</div>
</div>
<div class="form-group col-md-12">
<label for="password" class="col-md-3 control-label">
<spring:message code="password"></spring:message>
</label>
<div class="col-md-9">
<input type="password" name="password" class="form-control" placeholder='<spring:message code="password_instruction"></spring:message>' />
</div>
</div>
<input type="submit" class="btn btn-success col-md-offset-3" value='<spring:message code="login"></spring:message>' />
<input type="reset" class="btn btn-primary col-md-offset-1" value='<spring:message code="reset"></spring:message>' />
<a href="${path }/user/toRegister.action"><spring:message code="registerInstruction"></spring:message></a>
<p class="error">${msg }</p>
</form>
</div>
</div>
</body>
</html>
(4)运行结果截图:①中文、英文切换按钮:
图4.3 中文、英文切换按钮
②中文页面:图4.4 中文页面
③英文页面:图4.5 英文页面
5、SpringMVC配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd">
<!-- 只扫描Controller注解的类 -->
<context:component-scan base-package="com.remoa"
use-default-filters="false">
<context:include-filter type="annotation"
expression="org.springframework.stereotype.Controller" />
</context:component-scan>
<!-- 处理器适配器和处理器映射器 自动注册DefaultAnnotationHandlerMapping 与AnnotationMethodHandlerAdapter两个bean -->
<mvc:annotation-driven>
<mvc:message-converters>
<bean
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8</value>
<value>application/json;charset=UTF-8</value>
</list>
</property>
<!-- 通用json日期转换, @JsonFormat 优先级更高 -->
<property name="objectMapper">
<bean class="com.fasterxml.jackson.databind.ObjectMapper">
<property name="dateFormat">
<bean class="java.text.SimpleDateFormat">
<constructor-arg type="java.lang.String" value="yyyy-MM-dd HH:mm:ss" />
</bean>
</property>
</bean>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
<!-- 默认的注解支持 -->
<mvc:annotation-driven validator="validator"
conversion-service="conversion-service" />
<bean id="validator"
class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
<property name="providerClass" value="org.hibernate.validator.HibernateValidator" />
<!--不设置则默认为classpath下的 ValidationMessages.properties -->
<property name="validationMessageSource" ref="validatemessageSource" />
</bean>
<bean id="conversion-service"
class="org.springframework.format.support.FormattingConversionServiceFactoryBean" />
<bean id="validatemessageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:validatemessages" />
<property name="fileEncodings" value="utf-8" />
<property name="cacheSeconds" value="120" />
</bean>
<!-- 定义跳转的文件的前后缀 ,视图模式配置 -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 自动给后面action的方法return的字符串加上前缀和后缀,变成一个 可用的url地址 -->
<property name="prefix" value="/WEB-INF/pages/" />
<property name="suffix" value=".jsp" />
<property name="contentType" value="text/html; charset=utf-8" />
<property name="cache" value="false" />
</bean>
<!-- 异常处理 -->
<bean id="exceptionResolver"
class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="defaultErrorView">
<value>/error/500</value>
</property>
<property name="defaultStatusCode">
<value>500</value>
</property>
<!-- spring就会使用apache的org.apache.commons.logging.Log日志工具,记录这个异常,级别是warn -->
<property name="warnLogCategory">
<value>org.springframework.web.servlet.handler.SimpleMappingExceptionResolver
</value>
</property>
</bean>
<mvc:interceptors>
<!-- 国际化操作拦截器 如果采用基于(请求/Session/Cookie)则必需配置 -->
<bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" />
<!-- 全局的拦截器 -->
<bean class="com.remoa.user.action.LogHandlerInterceptor"></bean>
<!-- 局部拦截器 -->
<mvc:interceptor>
<mvc:mapping path="/user/*" />
<bean class="com.remoa.user.action.AuthHandlerInterceptor">
<property name="allowURIs">
<list>
<value>/login.action</value>
<value>/toRegister.action</value>
<value>/doregister.action</value>
<value>/checklogin.action</value>
<value>/lang.action</value>
</list>
</property>
</bean>
</mvc:interceptor>
</mvc:interceptors>
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<!-- 国际化信息所在的文件名 -->
<property name="basename" value="messages" />
<!-- 如果在国际化资源文件中找不到对应代码的信息,就用这个代码作为名称 -->
<property name="useCodeAsDefaultMessage" value="true" />
</bean>
<bean id="localeResolver"
class="org.springframework.web.servlet.i18n.SessionLocaleResolver">
<property name="defaultLocale" value="zh_CN"></property>
</bean>
</beans>