Spring MVC-08循序渐进之国际化(基于Session-SessionLocaleResolver)

简介: Spring MVC-08循序渐进之国际化(基于Session-SessionLocaleResolver)

概述


在Spring MVC中选择语言区域,可以使用语言解析器Bean,它包括几个实现,如下

  1. AcceptHeaderLocaleResolver
  2. SessionLocaleResolver
  3. CookieLocaleResolver

其中上篇博文 已经已经讲解了 Spring MVC-08循序渐进之国际化(AcceptHeaderLocaleResolver)

接下来我们来通过SessionLocaleResolver来实现国际化


工程结构


20180305111722449.png


实体类 标注了JSR303校验

package com.artisan.domain;
import java.io.Serializable;
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.NotBlank;
public class Product implements Serializable {
    private static final long serialVersionUID = 78L;
    @NotBlank
    @Size(min=1, max=10)
    private String name;
    private String description;
    private Float price;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getDescription() {
        return description;
    }
    public void setDescription(String description) {
        this.description = description;
    }
    public Float getPrice() {
        return price;
    }
    public void setPrice(Float price) {
        this.price = price;
    }
}


控制层

package com.artisan.controller;
import javax.validation.Valid;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import com.artisan.domain.Product;
@Controller
@RequestMapping("/product")
public class ProductController {
    private static final Log logger = LogFactory.getLog(ProductController.class);
    @RequestMapping(value="/product_input")
    public String inputProduct(Model model) {
        model.addAttribute("product", new Product());
        return "ProductForm";
    }
    @RequestMapping(value="/product_save")
    public String saveProduct(@Valid @ModelAttribute Product product, BindingResult bindingResult,
            Model model) {
        // 校验
        if (bindingResult.hasErrors()) {
            FieldError fieldError = bindingResult.getFieldError();
            logger.info("Code:" + fieldError.getCode() + " ,field:" + fieldError.getField());
            return "ProductForm";
        }
        // save product here
        model.addAttribute("product", product);
        return "ProductDetails";
    }
}


spring mvc配置文件

<?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:p="http://www.springframework.org/schema/p"
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd     
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">
    <!-- 扫描控制层的注解,使其成为Spring管理的Bean -->
    <context:component-scan base-package="com.artisan.controller" />
    <!-- 静态资源文件 -->
    <mvc:annotation-driven />
    <mvc:resources mapping="/css/**" location="/css/" />
    <mvc:resources mapping="/*.jsp" location="/" />
    <!-- 视图解析器 -->
    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>
    <!-- 国际化资源配置,资源文件绑定器-->
    <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <!-- 多语言配置的路径-->
        <property name="basename" value="/WEB-INF/resource/labels" />
        <!-- 如果在国际化资源文件中找不到对应代码的信息,就用这个代码作为名称 -->
        <property name="useCodeAsDefaultMessage" value="true" />
    </bean>
    <!--cookie方式 -->  
    <!-- 
        <bean id="cookieLocaleResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver" /> 
    -->  
    <!-- 动态切换国际化 ,国际化放在session中 -->
    <bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver"/>
    <!-- 国际化操作拦截器 如果采用基于(请求/Session/Cookie)则必需配置 -->
    <mvc:interceptors>
        <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
            <!-- 通过这个参数来决定获取那个配置文件 同页面?lang -->
            <property name="paramName" value="lang" />
        </bean>
    </mvc:interceptors>
</beans>


国际化资源文件

labels_en.properties

label.productName=Product Name
label.description=Description
label.price=Price
button.reset=Reset
button.submit=Add Product
form.name=Product Form
page.productform.title=Add Product


labels_zh.properties

label.productName=\u4ea7\u54c1\u540d\u79f0
label.description=\u63cf\u8ff0
label.price=\u4ef7\u683c
button.reset=\u91cd\u7f6e
button.submit=\u63d0\u4ea4
form.name=\u4ea7\u54c1\u8868\u5355
page.productform.title=\u4EA7\u54C1\u8868\u5355


labels.properties

label.productName=Product Name
label.description=Description
label.price=Price
button.reset=Reset
button.submit=Add Product
form.name=Product Form
page.productform.title=(default)New Product Form


labels.properties

label.productName=Product Name
label.description=Description
label.price=Price
button.reset=Reset
button.submit=Add Product
form.name=Product Form
page.productform.title=(default)New Product Form


页面

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE HTML>
<html>
<head>
<title><spring:message code="page.productform.title"/></title>
<style type="text/css">@import url("<c:url value="/css/main.css"/>");</style>
</head>
<body>
<div id="global">
Current Locale : ${pageContext.response.locale}
<br/>
Language : <a href="?lang=en">English</a>|<a href="?lang=zh">Chinese</a>
<form:form commandName="product" action="product_save" method="post">
    <fieldset>
        <legend><spring:message code="form.name" /></legend>
        <p>
            <label for="name"><spring:message code="label.productName" text="default text" />:</label>
            <form:input id="name" path="name" cssErrorClass="error"/>
            <form:errors path="name" cssClass="error"/>
        </p>
        <p>
            <label for="description"><spring:message code="label.description"/>: </label>
            <form:input id="description" path="description"/>
        </p>
        <p>
            <label for="price"><spring:message code="label.price" text="default text" />: </label>
            <form:input id="price" path="price" cssErrorClass="error"/>
        </p>
        <p id="buttons">
            <input id="reset" type="reset" tabindex="4"
                value="<spring:message code="button.reset"/>">
            <input id="submit" type="submit" tabindex="5" 
                value="<spring:message code="button.submit"/>">
        </p>
    </fieldset>
</form:form>
</div>
</body>
</html>


测试

tomcat中运行后,进行验证

选择英文

20180305111930192.png


选择中文


20180305111945943.png


源码


代码已提交到github

https://github.com/yangshangwei/SpringMvcTutorialArtisan

相关文章
|
11天前
|
Java 数据安全/隐私保护 网络架构
一个简单的示例在spring boot中实现国际化
一个简单的示例在spring boot中实现国际化
|
2天前
|
Java UED Spring
Spring Boot中的国际化(i18n)实现技巧
Spring Boot中的国际化(i18n)实现技巧
|
3天前
|
Java UED Spring
Spring Boot中的国际化配置
Spring Boot中的国际化配置
|
3天前
|
自然语言处理 Java UED
Spring Boot中的国际化配置
Spring Boot中的国际化配置
|
2月前
|
存储 Java Spring
Spring之国际化:i18n
【1月更文挑战第17天】 一、i18n概述 二、Java国际化 三、Spring6国际化 1、MessageSource接口 2、使用Spring6国际化
66 1
|
2月前
|
缓存 Java Spring
Spring Boot做国际化
Spring Boot做国际化
|
2月前
|
存储 人工智能 运维
spring国际化 - i18n
spring国际化 - i18n
53 0
|
2月前
|
存储 开发框架 自然语言处理
Spring6 i18n国际化
Spring6 i18n国际化
|
2月前
|
开发框架 前端开发 .NET
ASP.NET CORE 3.1 MVC“指定的网络名不再可用\企图在不存在的网络连接上进行操作”的问题解决过程
ASP.NET CORE 3.1 MVC“指定的网络名不再可用\企图在不存在的网络连接上进行操作”的问题解决过程
94 0
|
2月前
|
开发框架 前端开发 JavaScript
JavaScript云LIS系统源码ASP.NET CORE 3.1 MVC + SQLserver + Redis医院实验室信息系统源码 医院云LIS系统源码
实验室信息系统(Laboratory Information System,缩写LIS)是一类用来处理实验室过程信息的软件,云LIS系统围绕临床,云LIS系统将与云HIS系统建立起高度的业务整合,以体现“以病人为中心”的设计理念,优化就诊流程,方便患者就医。
38 0