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. 【Offer】[5] 【替换空格】

    题目描述 思路分析 Java代码 代码链接 题目描述 请实现一个函数,把字符串中的每个空格替换成"%20". 例如输入"We are happy.",则输出&q ...

  2. java 代理模式-静态代理与动态代理

    最近在研究SpringAOP,当然要学习AOP就要知道这么健硕.强大的功能的背后究竟隐藏着怎样不可告人的“秘密”?? 接下来就是查阅了许多资料详细的研究了一下Java的代理模式,感觉还是非常非常重要的 ...

  3. SpringCloud学习笔记(1):Eureka注册中心

    简介 Eureka是Netflix开源的基于rest的服务治理方案,分为Server端和Client端,Server端为注册中心,其他微服务通过Client端连接Server端进行服务的注册和发现. ...

  4. IDC是什么?

    IDC:互联网数据中心,是电信部门利用已有的互联网通信线路.贷款资源,建立标准化的电信专业级机房环境,为企业.政府提供服务器托管.服务器租用以及相关增值等方面服务.IDC是全球协作的特定设备网络,用来 ...

  5. mariadb+haproxy实现负载均衡(一)

    根据实际情况,数据生产无论是量还是使用地方都在稳步增加,单一服务器的稳定性也越来越受到关注,所以想提前做好技术准备. 因为之前就安装好了数据库,现在只讨论haproxy的安装及相关使用. haprox ...

  6. Python初步接触与学习

    Python的发展史与特点 诞生与发展史 1989,为了度过圣诞假期,Guido开始编写Python语言编译器.Python这个名字来自Guido的喜爱的电视连续剧<蒙蒂蟒蛇的飞行马戏团> ...

  7. vim编辑器的使用详解

    在Linux江湖,最常用到的编辑器非vim莫属,vim的功能很强大. 1.   vim简介 在Linux世界中,最长用到的而且功能比较强大的是Vim编辑器.Vim编辑器是在内存缓冲区中处理数据. vi ...

  8. Java定时发送邮件

    背景 甲方爸爸:新接入业务在国庆以及军运会期间需要每天巡检业务并发送邮件告知具体情况! 我司:没问题. 甲方爸爸:假期也要发噢. 我司:没问题(...). 刚开始计划指定几个同事轮流发送,业务只要不被 ...

  9. SpringBoot整合redis缓存(一)

    准备工作 1.Linux系统 2.安装redis(也可以安装docker,然后再docker中装redis,本文章就直接用Linux安装redis做演示) redis下载地址: 修改redis,开启远 ...

  10. 03: OpenGL ES 基础教程02 使用OpenGL ES 基本步骤

    第二章:让硬件为你工作(OpenGL ES 应用实践指南 iOS卷) 前言: 1:使用OpenGL ES 基本步骤 2:绘制三角形 3:效果 正文: 一:使用OpenGL ES 基本步骤 1:生成缓存 ...