下面是基于session的,springMVC国际花的一个例子:
需求是
输入url:展示中文界面
http://localhost:8080/MySSM/user?lang=zh
输入url: 展示英文界面
http://localhost:8080/MySSM/user?lang=en
下面是我demo项目的例子使用:
1.工程结构:
2.springMVC配置文件中 国际化相关的配置:
<!-- 存储区域设置信息 SessionLocaleResolver类通过一个预定义会话名将区域化信息存储在会话中。 --> <bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver" /> <!-- 国际化资源文件 --> <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource"> <property name="basename" value="classpath:messages" /> <!-- 如果在国际化资源文件中找不到对应代码的信息,就用这个代码作为名称 --> <property name="useCodeAsDefaultMessage" value="true" /> </bean> <mvc:interceptors> <!-- 该拦截器通过名为”lang”的参数来拦截HTTP请求,使其重新设置页面的区域化信息 --> <!-- <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" /> --> <bean class="com.cy.interceptor.LanguageInterceptor"> <property name="paramName" value="lang" /> </bean> </mvc:interceptors>
注意我重新使用了自己的拦截器:com.cy.interceptor.LanguageInterceptor
因为原来的拦截器org.springframework.web.servlet.i18n.LocaleChangeInterceptor,浏览器必须要输入lang=en_US,lang=zh_CN,才能改变语言。但是觉得输入这么多麻烦,因为一般就认为zh中文,en英文了。
3.语言LanguageInterceptor.java:
我只是把LocaleChangeInterceptor源代码拷贝了一部分过来;做些修改,主要是:
localeResolver.setLocale(request, response, newLocale)设置语言了;
package com.cy.interceptor; import java.util.Locale; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.LocaleResolver; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import org.springframework.web.servlet.support.RequestContextUtils; /** * 语言拦截器 * @author CY * */ public class LanguageInterceptor extends HandlerInterceptorAdapter{ /** * Default name of the locale specification parameter: "locale". */ public static final String DEFAULT_PARAM_NAME = "locale"; private String paramName = DEFAULT_PARAM_NAME; public void setParamName(String paramName) { this.paramName = paramName; } public String getParamName() { return this.paramName; } @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { Locale newLocale = getLocale(request.getParameter(getParamName())); LocaleResolver localeResolver = RequestContextUtils.getLocaleResolver(request); if (localeResolver == null) { throw new IllegalStateException("No LocaleResolver found: not in a DispatcherServlet request?"); } localeResolver.setLocale(request, response, newLocale); return true; } //根据language 获取Locale public static Locale getLocale(String language){ Locale locale = new Locale("zh", "CN");
if(language!=null && language.equals("en")){ locale = new Locale("en", "US"); } return locale; } }
4.如果想在controller中获取messages配置文件中的值怎么做呢?
下面是一部分代码:
import org.springframework.web.servlet.support.RequestContext; import org.springframework.web.servlet.support.RequestContextUtils; import java.util.ResourceBundle; @Controller public class UserController { private static Logger logger = Logger.getLogger(UserController.class); @Autowired private UserService userService; /** * 从国际化资源配置文件中根据key获取value 方法一 * @param request * @param key * @return */ public static String getMessage(HttpServletRequest request, String key){ Locale currentLocale = RequestContextUtils.getLocale(request); String lang = currentLocale.getLanguage(); ResourceBundle bundle = ResourceBundle.getBundle("messages_"+lang, currentLocale); return bundle.getString(key); } /** * 从国际化资源配置文件中根据key获取value 方法二 * @param request * @param key * @return */ public static String getMessage2(HttpServletRequest request, String key){ RequestContext requestContext = new RequestContext(request); String value = requestContext.getMessage(key); return value; } @RequestMapping("/user") public ModelAndView getUsers(HttpServletRequest request){ List<VoUser> userList = userService.getUsers(); ModelAndView mv = new ModelAndView(); //从message中获取文字 //String showUserInfo = getMessage(request, "showUserInfo"); String showUserInfo = getMessage2(request, "showUserInfo"); mv.addObject("showUserInfo", showUserInfo); mv.addObject("userList", userList); mv.setViewName("user"); return mv; } }
5.jsp中使用spring:message code:主要是:
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<spring:message code="userName"/>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <link rel="stylesheet" type="text/css" href="resources/bootstrap/bootstrap.min.css"> <title><spring:message code="userManage"/></title> <style type="text/css"> .container{ margin-top: 30px; } .imgclass{ height: 100px; } </style> </head> <body> <div class="container"> <p class="text-center bg-success">${showUserInfo}</p> <div class="form-horizontal"> <c:forEach var="user" items="${userList }"> <div class="form-group"> <label for="inputEmail3" class="col-sm-2 control-label"><spring:message code="userName"/></label> <div class="col-sm-10"> <input class="form-control" placeholder="Email" value="${user.name }"> </div> </div> <div class="form-group"> <label for="inputPassword3" class="col-sm-2 control-label"><spring:message code="age"/></label> <div class="col-sm-10"> <input class="form-control" placeholder="Password" value="${user.age }"> </div> </div> <div class="form-group"> <label for="inputPassword3" class="col-sm-2 control-label"><spring:message code="photoName"/></label> <div class="col-sm-10"> <input class="form-control" value="${user.photoName }"> </div> </div> <div class="form-group"> <label for="inputPassword3" class="col-sm-2 control-label"><spring:message code="photo"/></label> <div class="col-sm-10"> <img class="imgclass" src="getImg?username=${user.name }&photoName=${user.photoName}"/> </div> </div> </c:forEach> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <a href="toAddUser" class="btn btn-default"><spring:message code="addUser"/></a> </div> </div> </div> </div> </body> <script src="resources/js/jquery.min.js"></script> <script src="resources/bootstrap/bootstrap.min.js"></script> <script type="text/javascript"> $(function(){ }); </script> </html>
6.messages_zh.properties和messages_en.properties配置:
userManage=userManagement
userName=username
age=age
photoName=photo name
photo=photo
addUser=add user
showUserInfo=this is display user information
userManage=\u7528\u6237\u7BA1\u7406
userName=\u59D3\u540D
age=\u5E74\u9F84
photoName=\u7167\u7247\u540D\u79F0
photo=\u7167\u7247
addUser=\u589E\u52A0\u7528\u6237
showUserInfo=\u8FD9\u91CC\u662F\u5C55\u73B0\u7528\u6237\u4FE1\u606F
效果: