springmvc国际化设置

来源:互联网 发布:淘宝倒卖游戏币犯法吗 编辑:程序博客网 时间:2024/05/21 17:36

1、在spring配置文件中配置:

<!-- 国际化资源配置,资源文件绑定器-->    <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">        <!-- 国际化资源文件配置,指定properties文件存放位置 -->        <property name="basename" value="classpath:messages/message" />        <!-- 如果在国际化资源文件中找不到对应代码的信息,就用这个代码作为名称  -->                       <property name="useCodeAsDefaultMessage" value="true" />    </bean>    <!-- 动态切换国际化 ,国际化放在session中 -->    <bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver"></bean>    <mvc:interceptors>        <!-- 国际化操作拦截器 如果采用基于(请求/Session/Cookie)则必需配置 -->        <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">            <!-- 通过这个参数来决定获取那个配置文件 -->            <property name="paramName" value="language" />        </bean>    </mvc:interceptors>
配置中 <property name="basename" value="classpath:messages/message" /> 对应properties配置文件第一个下划线之前

<property name="paramName" value="language" />对应前端的<a href="?language=zh_CN">中文</a> | <a href="?language=en_US">英文</a>


2、配置properties文件

message_en_US.properties:

test.hello=hellotest.welcome=welcome

message_zh_CN.properties:

test.hello=\u4F60\u597Dtest.welcome=\u6B22\u8FCE\u60A8


3、前端welcome.jsp(两种方式实现,一种使用spring标签实现,后端不需要进行设置,另一种在后台转换直接传递到前端展示)

<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%><%@taglib prefix="spring" uri="http://www.springframework.org/tags" %><%@taglib prefix="mvc" uri="http://www.springframework.org/tags/form" %><!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"><title>Insert title here</title></head><body>选择语言:<a href="?language=zh_CN">中文</a> | <a href="?language=en_US">英文</a><br></br>(前台标签设置):<spring:message code="test.hello" /><br></br>(后台设置):${welcome}</body></html>


4、后台Controller设置:

/** * 国际化设置,跳转到welcome.jsp页面    * @param request * @param response * @return */@RequestMapping("view")    public ModelAndView view(HttpServletRequest request, HttpServletResponse response){        //spring翻译使用req.getmessage()方法        RequestContext req = new RequestContext(request);        ModelAndView model = new ModelAndView("welcome");        model.addObject("welcome", req.getMessage("test.welcome"));//后台设置        //model.addObject("welcome", LocaleLanguageUtil.loadMessage(request, "test.welcome"));//后台设置        return model;    }














原创粉丝点击