spring boot:用cookie保存i18n信息避免每次请求时传递参数(spring boot 2.3.3)

一,用cookie保存i18n信息的优点?

当开发一个web项目(非api站)时,如果把i18n的选择信息保存到cookie,

则不需要在每次发送请求时都传递所选择语言的参数,

也不需要增加header信息,

会使开发更方便更节省时间

说明:刘宏缔的架构森林是一个专注架构的博客,地址:https://www.cnblogs.com/architectforest

         对应的源码可以访问这里获取: https://github.com/liuhongdi/

说明:作者:刘宏缔 邮箱: 371125307@qq.com

二,演示项目的相关信息

1,项目地址

https://github.com/liuhongdi/international

2,项目功能说明

         演示了用cookie保存i18n信息

3,项目结构:如图:

 

三,配置文件说明

 1,pom.xml

        <!--thymeleaf begin-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <!--thymeleaf   end-->

2,application.properties

#error
server.error.include-stacktrace=always
#error
logging.level.org.springframework.web=trace

#thymeleaf
spring.thymeleaf.cache=false
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.mode=HTML
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html

#i18n,多个文件时要用逗号隔开,例:i18n.login,i18n.admin,i18n.goods
spring.messages.basename = i18n.login

说明:spring.messages.basename 用来指定语言的默认配置

3,i18n的properties文件:

login.properites

login.username=用户名
login.password=密码
login.btn=登录
login.remember = 自动登录
login.tip = 请输入用户名密码登录

login_zh_CN.properties

login.username=用户名
login.password=密码
login.btn=登录
login.remember = 自动登录
login.tip = 请输入用户名密码登录

login_en_US.properties

login.username=username
login.password=password
login.btn=Sign in
login.remember = Remember Me
login.tip = Please Sign in

四,java代码说明

1,MyLocaleResolver.java

//解析locale,采用cookie,避免每次都传递参数
public class MyLocaleResolver implements LocaleResolver {
    @Override
    public Locale resolveLocale(HttpServletRequest httpServletRequest) {
        //得到cookie,解析locale
        Cookie[] cookies = httpServletRequest.getCookies();
        Locale locale = Locale.getDefault();
        if(cookies != null) {
            for (Cookie cookie : cookies) {
                System.out.println(cookie.getName());
                System.out.println(cookie.getValue());
                if (cookie.getName().equals("selectedLang")) {
                    String temp = cookie.getValue();
                    if (!StringUtils.isEmpty(temp)) {
                        String[] s = temp.split("_");
                        locale = new Locale(s[0],s[1]);
                    }
                }
            }
        }
        /*通过参数解析locale
        String temp = httpServletRequest.getParameter("locale");
        Locale locale = Locale.getDefault();
        if (!StringUtils.isEmpty(temp)) {
            String[] s = temp.split("_");
            locale = new Locale(s[0],s[1]);
        }
        */
        return locale;
    }

    @Override
    public void setLocale(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) {

    }
}

2,MyLocaleResolverConfig.java

@Configuration
public class MyLocaleResolverConfig {
    @Bean
    public LocaleResolver localeResolver() {
        return new MyLocaleResolver();
    }
}

生成localRsolver的bean

3,LoginController.java

@Controller
@RequestMapping("/login")
public class LoginController {
    //登录页面
    @GetMapping("/login")
    public String login(Model model) {
        return "login/login.html";
    }
}

4,login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>login</title>
</head>
<body>
<div style="100%;height:30px;background:#ffffff;font-size: 16px;" ></div>
<div id="content" style="1040px;">
    <div style="790px;float:left;margin-left:30px;">
        <!--main begin-->
        <form class="form-signin" action="dashboard.html">
            <h1 class="h3 mb-3 font-weight-normal" th:text="#{login.tip}">Please sign in</h1>
            <label class="sr-only" th:text="#{login.username}">Username</label>
            <input type="text" class="form-control" placeholder="Username" th:placeholder="#{login.username}" required="" autofocus="">
            <br/>
            <br/>
            <label class="sr-only" th:text="#{login.password}">Password</label>
            <input type="password" class="form-control" placeholder="Password" th:placeholder="#{login.password}" required="">
            <div class="checkbox mb-3">
                <label>
                    <!--input是自闭标签所以使用 thymeleaf的行内写法-->
                    <input type="checkbox" value="remember-me"> [[#{login.remember}]]
                </label>
            </div>
            <button class="btn btn-lg btn-primary btn-block" type="submit" th:text="#{login.btn}">Sign in</button>
            <p class="mt-5 mb-3 text-muted">© 2017-2018</p>
            <a class="btn btn-sm" href="javascript:setLang('zh_CN')">中文</a>
            <a class="btn btn-sm" href="javascript:setLang('en_US')">English</a>
        </form>
        <!--main   end-->
    </div>
</div>
<script>
//设置选中的语言
function setLang(langName) {
    var exdays = 1;
    setCookie("selectedLang",langName,exdays);
    //刷新当前页面
    window.location.reload();
}

//设置cookie
function setCookie(cname,cvalue,exdays) {
    var d = new Date();
    d.setTime(d.getTime()+(exdays*24*60*60*1000));
    var expires = "expires="+d.toGMTString();
    document.cookie = cname + "=" + cvalue + "; " + expires;
}
</script>
</body>
</html>

五,测试效果

1,访问:

http://127.0.0.1:8080/login/login

返回:

点击下面的 中文 english两个链接可以看到效果:

  查看所保存的cookie

六,查看spring boot的版本

  .   ____          _            __ _ _
 /\ / ___'_ __ _ _(_)_ __  __ _    
( ( )\___ | '_ | '_| | '_ / _` |    
 \/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.3.3.RELEASE)
原文地址:https://www.cnblogs.com/architectforest/p/13560696.html