zoukankan      html  css  js  c++  java
  • SpringMVC系列(八)国际化

    一、页面国际化

    1.在pom.xml引入国际化需要的依赖

    1 <!--国际化相关依赖 begin  -->
    2     <dependency>
    3       <groupId>jstl</groupId>
    4       <artifactId>jstl</artifactId>
    5       <version>1.2</version>
    6     </dependency>
    7 <!--国际化相关依赖 end  -->

    2.在success.jsp里面添加jstl的fmt

    1 <%@ page language="java" contentType="text/html; charset=UTF-8"
    2     pageEncoding="UTF-8"%>
    3 <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>

    3.在springmvc.xml里面国际化资源文件

    1 <!-- 配置国际化资源文件 -->
    2     <bean id="messageSource"
    3         class="org.springframework.context.support.ResourceBundleMessageSource">
    4         <property name="basename" value="i18n"></property>    
    5     </bean>

    4.src/main/java新建国际化资源文件

    i18n.properties

    1 i18n.username=Username
    2 i18n.password=Password

    i18n_zh_CN.properties

    1 i18n.username=u7528u6237u540D
    2 i18n.password=u5BC6u7801

    i18n_en_US.properties

    1 i18n.username=Username
    2 i18n.password=Password

    5.在success.jsp页面通过jstl的标签获取值

    1 <!--国际化 begin  -->
    2 <p><b>国际化 begin</b></p>
    3 <fmt:message key="i18n.username"></fmt:message>
    4 <br>
    5 <fmt:message key="i18n.password"></fmt:message>
    6 <p><b>国际化 end</b></p>    
    7 <!--国际化 end  -->

     二、java代码国际化(依赖于i18n_zh_CN.properties和i18n_en_US.properties)

    1.注入ResourceBundleMessageSource

    1 @Autowired
    2 private ResourceBundleMessageSource messageSource;

    2. 通过getMessage方法获取国际化资源

    1 @RequestMapping("/i18n")
    2     public String testI18n(Locale locale){
    3         String val = messageSource.getMessage("i18n.user", null, locale);
    4         System.out.println(val); 
    5         return "i18n";
    6     }

    三、点击超链接切换语言进行页面国际化(全局国际化)

    (依赖于一的fmt标签、i18n_zh_CN.properties和i18n_en_US.properties)

    原理如下:

    1.LocaleChanceInterceptor拦截器获取local对象

    2. SessionLocalResolver解析器把local对象放到session里面

    3.应用程序从session里面获取local对象进行国际化

     1.在jsp页面设置语言切换链接

    1 <a href="i18n?locale=zh_CH">中文</a>
    2     
    3 <br><br>
    4 <a href="i18n?locale=en_US">英文</a>

    2.在springmvc.xml文件里面配置SessionLocaleResolver和LocaleChangeInterceptor

    1 <!-- 配置 SessionLocalResolver -->
    2     <bean id="localeResolver"
    3         class="org.springframework.web.servlet.i18n.SessionLocaleResolver"></bean>
    4     
    5     <mvc:interceptors>
    6 
    7         <!-- 配置 LocaleChanceInterceptor -->
    8         <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"></bean>
    9     </mvc:interceptors>
  • 相关阅读:
    Train Problem(栈的应用)
    Code obfuscatio (翻译!)
    Milking Cows
    Sorting a Three-Valued Sequence(三值排序)
    Asphalting Roads(翻译!)
    FatMouse' Trade
    Fibonacci Again
    Yogurt factory
    经济节约
    Lucky Conversion(找规律)
  • 原文地址:https://www.cnblogs.com/leeSmall/p/7821933.html
Copyright © 2011-2022 走看看