springmvc 资源国际化

<!--  
        关于国际化:
        1. 在页面上能够根据浏览器语言设置的情况对文本(不是内容), 时间, 数值进行本地化处理
        2. 可以在 bean 中获取国际化资源文件 Locale 对应的消息
        3. 可以通过超链接切换 Locale, 而不再依赖于浏览器的语言设置情况
        
        解决:
        1. 使用 JSTL 的 fmt 标签
        2. 在 bean 中注入 ResourceBundleMessageSource 的示例, 使用其对应的 getMessage 方法即可
        3. 配置 LocalResolver 和 LocaleChangeInterceptor
    -->    

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

i18n.properties
i18n_zh_CN.properties
i18n_en_US.properties

使用fmt标签在jsp页面显示i18n信息
<%@ 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 PAGE</a>
    
    
    
</body>
</html>

使用超链接国际化需要配置localeResolver
<br><br>
    <a href="i18n?locale=zh_CH">中文</a>
    
    <br><br>
    <a href="i18n?locale=en_US">英文</a>

    <!-- 配置 SessionLocalResolver -->
    <bean id="localeResolver"
        class="org.springframework.web.servlet.i18n.SessionLocaleResolver"></bean>
    
    <mvc:interceptors>
        <!-- 配置 LocaleChanceInterceptor -->
        <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"></bean>
    </mvc:interceptors>

@Autowired
    private ResourceBundleMessageSource messageSource;

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

直接跳转不通过controller
    <mvc:view-controller path="/i18n" view-name="i18n"/>
    <mvc:view-controller path="/i18n2" view-name="i18n2"/>

猜你喜欢

转载自www.cnblogs.com/znsongshu/p/10090447.html