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. webstorm的live templates快速编辑功能,让你的css JS代码书写速度飞起来

    前言: Emmet的前身是大名鼎鼎的Zen coding,如果你从事Web前端开发的话,对该插件一定不会陌生.它使用仿CSS选择器的语法来生成代码, 大大提高了HTML/CSS代码编写的速度,比如下面 ...

  2. Kafka服务端之网络连接源码分析

    #### 简介 上次我们通过分析KafkaProducer的源码了解了生产端的主要流程,今天学习下服务端的网络层主要做了什么,先看下 KafkaServer的整体架构图 ![file](https:/ ...

  3. 1.mssql和mysql sql如何调优?

    mssql是指微软的SQL Server数据库服务器. mssql常见的调优方法主要分为两类, (1)代码优化,代码优化,我搜集常用到的有以下几点: 1.避免使用select *  语句 2.避免关联 ...

  4. 简单说一下你对http和https的理解

    http是一种超文本传输协议,传输的数据都是未加密的,也就是显示在明面上的,是现在互联网上应用最为广泛的一种网络协议,相对来说不太安全,但是所需成本很小.http一般的端口号为80. https则是具 ...

  5. UGUI_游戏菜单场景切换

    事件委托 GameManger(空物体)+GameManger脚本——重要的方式 public class GameManger : MonoBehaviour { public void OnSta ...

  6. HDFS之Qurom Journal Manager(QJM)实现机制分析

    前言 1.1背景 自从hadoop2版本开始,社区引入了NameNode高可用方案.NameNode主从节点间需要同步操作日志来达到主从节点元数据一致.最初业界均通过NFS来实现日志同步,大家之所以选 ...

  7. ios 各个手机型号尺寸及分辨率适配

    常用宏 // 判断是否是ipad #define isPad ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdio ...

  8. 渐进深入理解Nginx

    文章原创于公众号:程序猿周先森.本平台不定时更新,喜欢我的文章,欢迎关注我的微信公众号. 之前其实写过一篇文章具体介绍过:最基础的Nginx教学,当时有提到过Nginx有一个重要的功能:负载均衡.所以 ...

  9. Uva 232 一个换行WA 了四次

    由于UVA OJ上没有Wrong anwser,搞的多花了好长时间去测试程序,之前一直以为改OJ有WA,后来网上一搜才知道没有WA,哎哎浪费了好长时间.此博客用来记录自己的粗心大意. 链接地址:htt ...

  10. Java连载34-对象的内存分析、对象之间建立关系

    一.内存分析 代码:引用可以是局部变量也可以是成员变量 public class Test1{ public static void main(String[] args){ User u = new ...