概述
在Spring MVC中选择语言区域,可以使用语言解析器Bean,它包括几个实现,如下
- AcceptHeaderLocaleResolver
- SessionLocaleResolver
- CookieLocaleResolver
其中上篇博文 已经已经讲解了 Spring MVC-08循序渐进之国际化(AcceptHeaderLocaleResolver)
接下来我们来通过SessionLocaleResolver来实现国际化
工程结构
实体类 标注了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
页面
<%@ 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中运行后,进行验证
选择英文
选择中文
源码
代码已提交到github