首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >springMVC配置 国际化实现中英文切换

springMVC配置 国际化实现中英文切换

作者头像
小柒2012
发布2018-04-13 16:23:41
1.3K0
发布2018-04-13 16:23:41
举报
文章被收录于专栏:IT笔记IT笔记

一.基于session的国际化实现:

首先配置我们项目的springservlet-mvc.xml文件添加的内容如下:

<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
        <!-- 国际化信息所在的文件名 -->                     
        <property name="basename" value="messages" />   
        <!-- 如果在国际化资源文件中找不到对应代码的信息,就用这个代码作为名称  -->               
        <property name="useCodeAsDefaultMessage" value="true" />           
    </bean>
    <mvc:interceptors>  
         <!-- 国际化操作拦截器 如果采用基于(请求/Session/Cookie)则必需配置 --> 
         <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" />  
    </mvc:interceptors>  
    <bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver" />

二、在项目中的源文件夹resources中添加messages.properties、messages_zh_CN.properties、messages_en_US.properties三个文件,其中messages.properties、messages_zh_CN.properties里面的"money", "date",为中文,messages_en_US.properties里面的为英文。 三、配置index.jsp

<%@ page contentType='text/html; charset=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=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<a href="switch?langType=zh">中文</a> | <a href="switch?langType=en">英文</a><br/>
<spring:message code="index"/>
</br>
哈哈哈哈 这是个主页
</body>
</html>

四、后台配置

/**
 * 中英文语言切换
 * 创建者    张志朋
 * 创建时间    2016年8月1日
 *
 */
@Controller
public class GlobalController extends BaseController {
    
    @RequestMapping(value="/switch", method = {RequestMethod.GET})
    public String test(HttpServletRequest request,Model model, @RequestParam(value="langType", defaultValue="zh") String langType){
            
            if(langType.equals("zh")){
                Locale locale = new Locale("zh", "CN"); 
                request.getSession().setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME,locale); 
            }
            else if(langType.equals("en")){
                Locale locale = new Locale("en", "US"); 
                request.getSession().setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME,locale);
            }
            else {
                request.getSession().setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME,LocaleContextHolder.getLocale());
            }
        return "modules/index";
    }
    
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2016-08-01,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档