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. 在docker上编译openjdk8

    以前曾经试过在VMware上安装linux,再在linux上编译openjdk8,但是每次都不顺利,例如linux环境,预装依赖软件,openjdk源码的选择等环境都会遇到问题,一旦失败再重新开始挺费 ...

  2. 了解css中px、em、rem的区别并使用Flexible实现vue移动端的适配

    本人java菜鸟一名,若有错误,还请见谅. 1.px和em和rem的定义和区别 px:px像素,是相对单位,相对于屏幕的分辨率而言,也就是说,当屏幕的分辨率不同那么px相同,实际看到的大小也会不同. ...

  3. 【Redis】缓存穿透与缓存雪崩

    一.缓存雪崩 1.1 缓存雪崩产生的原因 1.2 解决方案 1.3 锁的方式 1.4 消息中间件 1.5 一级和二级缓存 1.6 均摊分配redis key 失效时间 二.缓存穿透 一.缓存雪崩 1. ...

  4. 深入拆解Java虚拟机视频教程

    目录: 第1节说在前面的话   00:05:07分钟   | 第3节环境搭建以及jdk,jre,jvm的关系   00:20:48分钟   | 第5节jvm再体验-jvm可视化监控工具   00:21 ...

  5. springboot中动态修改logback日志级别

    springboot中动态修改logback日志级别 在spring boot中使用logback日志时,项目运行中,想要修改日志级别. 代码如下: import org.slf4j.Logger; ...

  6. MySQL索引原理及SQL优化

    目录 索引(Index) 索引的原理 b+树 MySQL如何使用索引 如何优化 索引虽好,不可滥用 如何验证索引使用情况? SQL优化 explain查询执行计划 id select_type tab ...

  7. equals、==、hashCode

    equals和==的区别 ==主要用来比较基本数据类型,而equal主要用来比较对象是否相等.equal是Object的方法. 如果两者都用来比较对象的相等性,那么如果两个引用地址相同,那么==就返回 ...

  8. 时钟AnalogClock和DigitalClock

    <AnalogClock android:layout_width="fill_parent" android:layout_height="fill_parent ...

  9. 〈一〉ElasticSearch的介绍

    目录 什么是ElasticSearch 核心能力 ES的搜索核心 搜索引擎选择 搜索的处理 补充: 小节总结: 基本学习环境搭建 如何操作ElasticSearch 下载.安装和运行(Based Wi ...

  10. C++ 基础中的基础 ---- 引用

    C++ 基础中的基础 ---- 引用 引用的概念:引用变量是一个别名,也就是说,它是某个已存在变量的另一个名字.一旦把引用初始化为某个变量,就可以使用该引用名称或变量名称来指向变量.比如: int n ...