springboot+thymeleaf國際化方法一:LocaleResolver

springboot中大部分有默認配置因此開發起項目來很是迅速,僅對需求項作單獨配置覆蓋便可html

spring採用的默認區域解析器是AcceptHeaderLocaleResolver,根據request header中的accept-language值來解析locale,而且是不可變的。java

那麼想要實現國際化,就要使用SessionLocaleResolver或者CookieLocaleResolver。正如類的名字所示,是按session或cookie中儲存的locale值來解析locale。web

我就以SessionLocaleResolver舉例:spring

1.創建一個配置類springboot

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" 是必須的cookie

優先級以下:session

session中對應屬性(3中有說明)有值則按session來app

若是沒有可是SessionLocaleResolver設置了默認的locale則按默認值來this

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

再而後就仍是按request header中的accept-language值來spa

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

相關文章
相關標籤/搜索