springmvc 國際化

目標:html

1、在頁面上根據瀏覽器語言設置的狀況顯示不一樣的文本內容、時間java

一、編寫國際化資源文件web

i18n_en_US.propertiesspring

i18n_zh_CN.properties瀏覽器

i18n.propertiessession

內容以下:mvc

NotEmpty=..不能爲空
Email=..不是一個合法的電子郵件
i18n.user=User
i18n.password=Password
NotEmpty=..不能爲空
Email=..不是一個合法的電子郵件
i18n.user=用戶名
i18n.password=密碼

二、配置獲取資源文件的bean ResourceBundleMessageResource 配置文件名basename 配置資源文件的默認編碼格式defaultEncodingapp

    <bean id="messageSource"
        class="org.springframework.context.support.ResourceBundleMessageSource">
        <property name="basename" value="i18n"></property>
        <property name="defaultEncoding" value="utf-8"></property>
    </bean>
    

三、編寫測試視圖jsp,使用fmt標籤引入jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<!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>
<fmt:message key="i18n.user"></fmt:message>
<br>
<br>
<a href="i18n2">i18n2</a>
</body>
</html>

四、配置視圖測試

<mvc:view-controller path="/i18n" view-name="i18n"/>

2、可以在bean中獲取國際化資源文件對應的locale信息

一、在handler中映射鏈接,注入 bean ResourceBunderResourceMessage 

二、經過Resource bean 的getMessage方法獲取locale的信息

@RequestMapping("/i18n")
    public String testI18n(Locale locale) {
        System.out.println(resourceBundleMessageSource.getMessage("i18n.user", null, locale));
        System.out.println(locale.getCountry());
        return "i18n";
    }

3、可以根據超連接切換locale,再也不依賴於瀏覽器語言設置

原理:經過攔截器根據連接穿過來的name=locale信息獲取locale,將locale存入session中,從session中取locale對象,使用locale對象

 

一、配置sessionLocaleResolver

<!-- 配置sessionLocaleResolver -->
    <bean id="localeResolver"
        class="org.springframework.web.servlet.i18n.SessionLocaleResolver"></bean>

 

二、配置LocaleChangeIntercepter

<!-- 配置LocaleChangeIntercepter -->
    <mvc:interceptors>
        <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"></bean>
    </mvc:interceptors>

 

三、編寫一個測試連接

<br>
<br>
<a href="i18n?locale=zh_CH">中文</a>

<br>
<br>
<a href="i18n?locale=en_US">English</a>
相關文章
相關標籤/搜索