springboot中大部分有默认配置所以开发起项目来非常迅速,仅对需求项做单独配置覆盖即可

spring采用的默认区域解析器是AcceptHeaderLocaleResolver,根据request header中的accept-language值来解析locale,并且是不可变的。

那么想要实现国际化,就要使用SessionLocaleResolver或者CookieLocaleResolver。正如类的名字所示,是按session或cookie中储存的locale值来解析locale。

我就以SessionLocaleResolver举例:

1.建立一个配置类

package com.example.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.i18n.SessionLocaleResolver; /**
* Created by wq on 2016/8/15.
*/
@Configuration
public class SpringMVC_config {
@Bean(name="localeResolver")
public LocaleResolver localeResolverBean() {
return new SessionLocaleResolver();
}
// @Bean(name="messageSource")
// public ResourceBundleMessageSource resourceBundleMessageSource(){
// ResourceBundleMessageSource source=new ResourceBundleMessageSource();
// source.setBasename("messages");
// return source;
// }
}

注意 name="localeResolver" 是必须的

优先级如下:

session中对应属性(3中有说明)有值则按session来

如果没有但是SessionLocaleResolver设置了默认的locale则按默认值来

//        SessionLocaleResolver localeResolver=new SessionLocaleResolver();
// localeResolver.setDefaultLocale(Locale.ENGLISH);

再然后就还是按request header中的accept-language值来

2.建立对应的messages.properties

messages.properties

messages_en.properties

messages_zh_CN.properties

前面注释的代码则可以修改properties的前缀部分,name="messageSource" 同样是必须的

比如 setBasename("msg"); 对应properties则为

msg.properties

msg_en.properties

msg_zh_CN.properties

格式上sys.test=hello、sys.test=你好,应该无需赘述(可能转码会避免一些问题,我这里直接放的中文)

3.controller中切换locale

package com.example.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.LocaleResolver; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Locale; import static org.springframework.web.servlet.i18n.SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME; /**
* Created by Administrator on 2016/6/11.
*/
@Controller
public class DemoController {
@Autowired
LocaleResolver localeResolver; @RequestMapping("test")
public String test(HttpServletRequest request, HttpServletResponse response) {
HttpSession session=request.getSession();
localeResolver.setLocale(request,response,Locale.ENGLISH);
System.out.println(session.getAttribute(LOCALE_SESSION_ATTRIBUTE_NAME));
return "messages";
}
}

这里org.springframework.web.servlet.i18n.SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME这个字符串常量则是session中默认属性名

可以看一下SessionLocaleResolver的部分源码

public class SessionLocaleResolver extends AbstractLocaleContextResolver {
public static final String LOCALE_SESSION_ATTRIBUTE_NAME = SessionLocaleResolver.class.getName() + ".LOCALE";
public static final String TIME_ZONE_SESSION_ATTRIBUTE_NAME = SessionLocaleResolver.class.getName() + ".TIME_ZONE";

locale默认属性名为

org.springframework.web.servlet.i18n.SessionLocaleResolver.LOCALE

setLocale是抽象类AbstractLocaleContextResolver中方法

    public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {
this.setLocaleContext(request, response, locale != null?new SimpleLocaleContext(locale):null);
}

然后看SessionLocaleResolver中setLocaleContext

    public void setLocaleContext(HttpServletRequest request, HttpServletResponse response, LocaleContext localeContext) {
Locale locale = null;
TimeZone timeZone = null;
if(localeContext != null) {
locale = localeContext.getLocale();
if(localeContext instanceof TimeZoneAwareLocaleContext) {
timeZone = ((TimeZoneAwareLocaleContext)localeContext).getTimeZone();
}
} WebUtils.setSessionAttribute(request, LOCALE_SESSION_ATTRIBUTE_NAME, locale);
WebUtils.setSessionAttribute(request, TIME_ZONE_SESSION_ATTRIBUTE_NAME, timeZone);
}

本质上就是一些非空判断取默认,最终给session中的对应属性赋值

4.thymeleaf页面中调用

<!DOCTYPE html>
<html lang="zh_CN"
xmlns:th="http://www.thymeleaf.org">
<head>
<title>msg</title>
</head>
<body>
<h1 th:text="${#locale}"></h1>
<h1 th:text="#{sys.test}"></h1>
</body>
</html>

则显示en hello

为了以防万一我还是在上文标红了= =#

end of story

springboot+thymeleaf国际化方法一:LocaleResolver的更多相关文章

  1. org.springframework.expression.spel.SpelEvaluationException: EL1004E: Method call: Method service() cannot be found on com.my.blog.springboot.thymeleaf.util.MethodTest type

    前言 本文中提到的解决方案,源码地址在:springboot-thymeleaf,希望可以帮你解决问题. 至于为什么已经写了一篇文章thymeleaf模板引擎调用java类中的方法,又多此一举的单独整 ...

  2. springboot+thymeleaf+pageHelper带条件分页查询

    html层 <div> <a class="num"><b th:text="'共 '+ ${result.resultMap['pages ...

  3. springboot+thymeleaf简单使用

    关于springboot想必很多人都在使用,由于公司项目一直使用的是SpringMVC,所以自己抽空体验了一下springboot的简单使用. 环境搭建 springbooot的环境搭建可以说很灵活, ...

  4. SpringBoot thymeleaf使用方法,thymeleaf模板迭代

    SpringBoot thymeleaf使用方法,thymeleaf模板迭代 SpringBoot thymeleaf 循环List.Map ============================= ...

  5. SpringBoot thymeleaf模板页面没提示,SpringBoot thymeleaf模板插件安装

    SpringBoot thymeleaf模板插件安装 SpringBoot thymeleaf模板Html页面没提示 SpringBoot  thymeleaf模板页面没提示 SpringBoot t ...

  6. SpringBoot thymeleaf模板版本,thymeleaf模板更换版本

    SpringBoot thymeleaf模板版本 thymeleaf模板更换版本 修改thymeleaf模板版本 ================================ ©Copyright ...

  7. Springboot+Thymeleaf框架的button错误

    ---恢复内容开始--- 在做公司项目时,遇到了一个Springboot+Thymeleaf框架问题: 使用框架写网站时,没有标明type类型的button默认成了‘submit’类型,每次点击按钮都 ...

  8. SpringBoot+Thymeleaf+iView

    SpringBoot+Thymeleaf参考: https://www.cnblogs.com/kibana/p/10236187.html 1.Controller: package cn.mmwe ...

  9. layui表格数据渲染SpringBoot+Thymeleaf返回的数据时报错(Caused by: org.attoparser.ParseException: Could not parse as expression: ")

    layui table渲染数据时报错(Caused by: org.attoparser.ParseException: Could not parse as expression: ") ...

随机推荐

  1. Request请求的应用

    1.通过request获得请求行 获得客户端的请求方式:String getMethod() 获得请求的资源: String getRequestURI()   StringBuffer getReq ...

  2. 【DataBase】事务

    一.事务概述 二.事务的四大特性(ACID) 三.事务的隔离性导致的问题 四.数据库的四个隔离级别 五.数据库中的锁机制: 六.更新丢失 七.并发事务所带来的的问题 一.事务概述 事务的概念:事务是指 ...

  3. 实现 Java 本地缓存,该从这几点开始

    缓存,我相信大家对它一定不陌生,在项目中,缓存肯定是必不可少的.市面上有非常多的缓存工具,比如 Redis.Guava Cache 或者 EHcache.对于这些工具,我想大家肯定都非常熟悉,所以今天 ...

  4. Java中String为什么是不可变的

    1.在Java中,String类是不可变类,一个不可变类是一个简单的类,并且这个的实例也不能被修改, 这个类的实例创建的时候初始化所有的信息,并且这些信息不能够被修改 2.字符串常量池 字符串常量池是 ...

  5. SpringMVC的工作原理图

    SpringMVC的工作原理图: SpringMVC流程 1.  用户发送请求至前端控制器DispatcherServlet. 2.  DispatcherServlet收到请求调用HandlerMa ...

  6. Could not calculate build plan :lugin org.apache.maven.plugins:maven-resources-plugin:2.6 or one of

    eclipse中新建maven项目,出现 Could not calculate build plan :lugin org.apache.maven.plugins:maven-resources- ...

  7. Python(Head First)学习笔记:一

    目录: 1 认识Python:Python的特点.安装.开发环境搭建 2 共享代码:连接共享社区.语法.函数.技巧 3 文件与异常:调试.处理错误.迭代.改进.完善 4 持久存储:文件存储.读写 5 ...

  8. FreeSql (三十二)Aop

    FreeSql AOP 已有的功能介绍,未来为会根据用户需求不断增强. 审计 CRUD 马云说过,996是修福报.对于多数程序员来说,加班是好事...起码不是闲人,不会下岗. 当如果因为某个 sql ...

  9. DevExpress的对话框XtraMessageBox的使用

    场景 在Winform中一般弹出对话框使用的是MessageBox,而在 DevExpress中使用的是XtraMessageBox实现对话框. 效果 实现 首先新建确认按钮的调用方法: public ...

  10. 菜鸟 ssm 框架的学习之路

    跟着老师学习了两个月的java语言,现在学习到了框架的部分,一直想在博客上写点东西的,只是自己一直没有时间,其实到底也是懒,鲁迅说过:"时间就像海绵里的水,只要愿意去挤还是有的", ...