springmvc 基于session实现国际化

国际化(internationalization)是设计和制造容易适应不同区域要求的产品的一种方式。它要求从产品中抽离所有地域语言,国家/地区和文化相关的元素。换言之,应用程序的功能和代码设计考虑在不同地区运行的需要,其代码简化了不同本地版本的生产。开发这样的程序的过程,就称为国际化。
springmvc提供了对国际化的支持。其实现国际化有多种方式,我们讲一下其中基于session实现的国际化。
举个例子:要求显示一个表格,可以实现中英文的切换。

定义资源文件

在src下定义中文的资源文件,i18n_zh_CN.properties,代码如下:

name=\u59D3\u540D
age=\u5E74\u9F84
gerdar=\u6027\u522B

在src下定义英文的资源文件,i18n_en_US.properties,代码如下:

name=name
gerdar=gerdar
age=age

在springmvc文件中配置国际化

springmvc.xml,代码如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd"
>


    <!-- 扫描service -->
    <context:component-scan base-package="com.hzit.service">

    </context:component-scan>
    <!-- 识别controller -->
    <!-- 扫描bao 识别controller -->
    <context:component-scan base-package="springmvc02,com.hzit.controller">
        <context:include-filter type="annotation"
            expression="org.springframework.stereotype.Controller" />

    </context:component-scan>


    <!-- 开启mvc的注解 -->
    <mvc:annotation-driven></mvc:annotation-driven>
    <!-- <mvc:annotation-driven validator="validator"></mvc:annotation-driven> -->
    <!-- <bean id="validator" -->
    <!-- class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"> -->
    <!-- <property name="providerClass" value="org.hibernate.validator.HibernateValidator" 
        /> -->

    <!-- </bean> -->

    <!-- 配置一个视图解析器 -->
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">

        <!-- 视图jsp所在目录(地址) -->
        <property name="prefix" value="/WEB-INF/jsp/"></property>
        <property name="suffix" value=""></property>
    </bean>
    <!-- 文件上传 -->
    <bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">

        <!-- 总文件大小 -->
        <property name="maxUploadSize" value="50000000"></property>
        <!-- 单文件大小 -->
        <property name="maxUploadSizePerFile" value="5000000"></property>
        <property name="defaultEncoding" value="UTF-8"></property>
    </bean>

    <!-- -->
    <!-- 方式一:解决静态资源访问 -->
    <!-- <mvc:resources location="/images/" mapping="/images/**"></mvc:resources> -->
    <!-- <mvc:resources location="/upload/" mapping="/upload/**"></mvc:resources> -->
    <!-- 方式二:解决静态资源访问 -->
    <mvc:default-servlet-handler />

    <!-- 国际化的配置 -->
    <bean id="messageSource"
        class="org.springframework.context.support.ReloadableResourceBundleMessageSource">

        <property name="basename" value="classpath:i18n"></property>
        <property name="useCodeAsDefaultMessage" value="true"></property>
    </bean>

    <!--国际化实现的第一种方式:借助消息头实现:Accept-Language  -->
<!--     <bean id="localeResolver" class="org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver"></bean> -->
    <!--国际化实现的第二种方式:借助HttpSession  -->
    <bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver"></bean>
    <!--如果国际化是通过Session或Cookie实现的,那么需要配置拦截器  -->

   <!-- 配置 LocaleChangeInterceptor 从请求参数中获取本次请求对应本地化类型。
     * 第一步,获取name=locale的请求参数,默认情况是请求参数名为locale,可以配
     置paramName来调整。
     * 第二步,把locale的请求参数解析为Locale对象。
     * 第三步,获取LocaleResolver对象。
    -->    
    <mvc:interceptors>
<!--         <bean class="com.hzit.interceptors.TimerInterceptor"></bean> -->
<!--         <bean class="com.hzit.interceptors.MyInterceptor"></bean> -->
        <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
            <property name="paramName" value="locale"></property>
        </bean>
    </mvc:interceptors>
    <import resource="springmvc2.xml" />

</beans>

定义测试controller类

TestI18nController,其代码如下:

package springmvc02;

import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;
import org.springframework.web.servlet.support.RequestContext;

@Controller
public class TestI18nController {

    @Autowired
    private ReloadableResourceBundleMessageSource messageSource;

    /**
     * 基于浏览器实现的国际化,要求浏览器的语言设置
     * 
     * @param request
     * @param map
     * @return
     */

    @RequestMapping("/disByLocale")
    public String disByLocale(HttpServletRequest request, Map<String, Object> map) {
        RequestContext requestContext = new RequestContext(request);
        System.out.println(">>>>>>>>" + requestContext.getLocale());
        map.put("name", requestContext.getMessage("name"));
        map.put("age", requestContext.getMessage("age"));
        map.put("gerdar", requestContext.getMessage("gerdar"));
        return "disByLocal.jsp";
    }



    // 基于Session的实现
    @RequestMapping("/disBySession")
    public String disBySession(String locale, HttpSession session) {
        Locale locale2;// 国际化语言信息
        System.out.println(locale);
        switch (locale) {
        case "zh":// 中文
            // 参数说明:1、语言2、国家
            locale2 = new Locale("zh""CN");
            break;
        case "en":// 英文
            locale2 = new Locale("en""US");
            break;
        default:
            // 获取默认的国际化
            locale2 = LocaleContextHolder.getLocale();
            break;
        }

        // 设置属性标记当前的语言环境
        session.setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME, locale2);
        return "disBySession.jsp";
    }
}

定义jsp页面

disBySession.jsp,显示表格,代码如下:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>

<%@ page import="java.util.*,org.springframework.web.servlet.i18n.*" %>
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring" %>
<!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>基于session的国际化测试</title>
<style>
table {
    width60%;border-spacing:0;
}
td {
    width:50%;
    border1px solid red;
}
</style>
</head>
<body>

    当前语言: ${pageContext.response.locale }<br>
    <table>
        <tr>
            <td><spring:message code="name" scope="session"></spring:message></td>
            <td></td>
        </tr>
        <tr>
            <td><spring:message code="age"></spring:message></td>
            <td></td>
        </tr>
        <tr>
            <td><spring:message code="gerdar"></spring:message></td>
            <td></td>
        </tr>
    </table>
    <a href="?locale=zh">中文</a> <a href="?locale=en">英文</a>
</body>
</html>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值