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="width:100%;height:30px;background:#ffffff;font-size: 16px;" ></div>
<div id="content" style="width:1040px;">
    <div style="width: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)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM