溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Spring Boot Thymeleaf實(shí)現(xiàn)國(guó)際化的方法詳解

發(fā)布時(shí)間:2020-09-20 19:40:22 來源:腳本之家 閱讀:202 作者:云天 欄目:編程語(yǔ)言

前言

開發(fā)傳統(tǒng)Java WEB工程時(shí),我們可以使用JSP頁(yè)面模板語(yǔ)言,但是在SpringBoot中已經(jīng)不推薦使用了。SpringBoot支持如下頁(yè)面模板語(yǔ)言

  • Thymeleaf
  • FreeMarker
  • Velocity
  • Groovy
  • JSP

上面并沒有列舉所有SpringBoot支持的頁(yè)面模板技術(shù)。其中Thymeleaf是SpringBoot官方所推薦使用的,下面來談?wù)凾hymeleaf實(shí)現(xiàn)應(yīng)用國(guó)際化方法。

ps:當(dāng)然現(xiàn)在開發(fā)基本上是前后端分離了,但是難免需要維護(hù)遺留項(xiàng)目或沒有條件前后端分離的團(tuán)隊(duì)還是有很多的,這時(shí)候?qū)W會(huì)必要的前端技能,能達(dá)到事半功倍的效果。

添加Thymeleaf依賴

要想使用Thhymeleaf,首先要在pom.xml文件中單獨(dú)添加Thymeleaf依賴。

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

Spring Boot默認(rèn)存放模板頁(yè)面的路徑在src/main/resources/templates或者src/main/view/templates,這個(gè)無論是使用什么模板語(yǔ)言都一樣,當(dāng)然默認(rèn)路徑是可以自定義的,不過一般不推薦這樣做。另外Thymeleaf默認(rèn)的頁(yè)面文件后綴是.html

什么是國(guó)際化

國(guó)際化(internationalization)是設(shè)計(jì)和制造容易適應(yīng)不同區(qū)域要求的產(chǎn)品的一種方式。它要求從產(chǎn)品中抽離所有地域語(yǔ)言,國(guó)家/地區(qū)和文化相關(guān)的元素。換言之,應(yīng)用程序的功能和代碼設(shè)計(jì)考慮在不同地區(qū)運(yùn)行的需要,其代碼簡(jiǎn)化了不同本地版本的生產(chǎn)。開發(fā)這樣的程序的過程,就稱為國(guó)際化。

Spring Boot Thymeleaf 代碼實(shí)現(xiàn)國(guó)際化

1.配置文件代碼WebConfiguration.java

package com.easy.templateThymeleaf.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;

import java.util.Locale;

@Configuration
public class WebConfiguration implements WebMvcConfigurer {

 @Bean
 public LocaleResolver localeResolver() {

  SessionLocaleResolver localeResolver = new SessionLocaleResolver();
  localeResolver.setDefaultLocale(new Locale("es", "ES"));
  return localeResolver;
 }

 @Bean
 public LocaleChangeInterceptor localeChangeInterceptor() {

  LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor();
  localeChangeInterceptor.setParamName("lang");
  return localeChangeInterceptor;
 }

 @Override
 public void addInterceptors(InterceptorRegistry registry) {

  registry.addInterceptor(localeChangeInterceptor());
 }
}

2.控制器代碼IndexController.java、LocaleController.java

package com.easy.templateThymeleaf.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.Locale;

@Controller
public class IndexController {

 @Autowired
 private MessageSource messageSource;

 @RequestMapping(value = {"/index", "/"}, method = RequestMethod.GET)
 public String index(Model model, Locale locale) {

  model.addAttribute("title", messageSource.getMessage("text.title", null, locale));
  return "index";
 }
}
package com.easy.templateThymeleaf.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import javax.servlet.http.HttpServletRequest;

@Controller
public class LocaleController {

 @GetMapping(value = "/locale")
 public String localeHandler(HttpServletRequest request) {

  String lastUrl = request.getHeader("referer");
  return "redirect:" + lastUrl;
 }
}

3.靜態(tài)頁(yè)面代碼index.html

<!DOCTYPE html>
<html xmlns:th="https://www.thymeleaf.org">
<head>
 <meta charset="UTF-8">
 <title th:text="${title}">Insert title here</title>

 <link rel="stylesheet" th:href="@{/css/bootstrap.min.css}">
</head>
<body>

<nav class="navbar navbar-expand-lg navbar-dark bg-danger">
 <a class="navbar-brand" th:href="@{'/'}">I18N Demo</a>
 <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav"
   aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
  <span class="navbar-toggler-icon"></span>
 </button>
 <div class="collapse navbar-collapse" id="navbarNav">
  <ul class="navbar-nav mr-auto">
   <li class="nav-item active">
    <a class="nav-link" th:href="@{'/'}" th:text="#{text.home}">Home</a>
   </li>
  </ul>
  <ul class="navbar-nav navbar-right">
   <li class="dropdown">
    <button th:text="#{text.language}" class="btn btn-danger dropdown-toggle" type="button"
      id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
    </button>
    <div class="dropdown-menu dropdown-menu-right" aria-labelledby="dropdownMenuButton">
     <a class="dropdown-item" th:href="@{/locale(lang=es_ES)}"
      th:text="#{text.language.chinese}">中文</a>
     <a class="dropdown-item" th:href="@{/locale(lang=en_US)}"
      th:text="#{text.language.english}">英語(yǔ)</a>
    </div>
   </li>
  </ul>
 </div>
</nav>

<div class="container" >

 <div class="jumbotron jumbotron-fluid">
  <div class="container">
   <h2 class="display-4" th:text="#{text.home.message}">Fluid jumbotron</h2>
   <p class="lead" th:text="#{text.description}">This is a modified jumbotron that occupies the entire
    horizontal space of its parent.</p>
  </div>
 </div>

</div>

<footer>

 <script th:src="@{/js/jquery-3.3.1.min.js}"></script>
 <script th:src="@{/js/popper.min.js}"></script>
 <script th:src="@{/js/bootstrap.min.js}"></script>

</footer>

</body>
</html>

4.語(yǔ)言配置文件

中文簡(jiǎn)體語(yǔ)言配置文件messages.properties

text.title=國(guó)際化示例
text.home=首頁(yè)
text.language=語(yǔ)言
text.language.chinese=中文(簡(jiǎn)體)
text.language.english=英語(yǔ)
text.home.message=你好,歡迎你
text.description=這是個(gè)國(guó)際化模板示例

英文語(yǔ)言配置文件messages.properties

text.title=Application title
text.home=Home
text.language=Language
text.language.chinese=Chinese
text.language.english=English
text.home.message=Hi, welcome!
text.description=It is a i18n demo

5.最后貼上maven配置文件pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 <modelVersion>4.0.0</modelVersion>
 <parent>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-parent</artifactId>
  <version>2.1.7.RELEASE</version>
  <relativePath/> <!-- lookup parent from repository -->
 </parent>
 <groupId>com.easy</groupId>
 <artifactId>template-thymeleaf</artifactId>
 <version>0.0.1</version>
 <name>template-thymeleaf</name>
 <description>Demo project for Spring Boot</description>

 <properties>
  <java.version>1.8</java.version>
  <encoding>UTF-8</encoding>
  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
 </properties>

 <dependencies>
  
  <dependency>
   <groupId>com.h3database</groupId>
   <artifactId>h3</artifactId>
   <scope>runtime</scope>
  </dependency>

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

  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
  </dependency>

  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-test</artifactId>
   <scope>test</scope>
  </dependency>

  <dependency>
   <groupId>org.projectlombok</groupId>
   <artifactId>lombok</artifactId>
   <optional>true</optional>
  </dependency>

 </dependencies>

 <build>
  <plugins>
   <plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
   </plugin>
  </plugins>
 </build>

</project>

運(yùn)行示例

1.找到TemplateThymeleafApplication.java文件運(yùn)行示例

地址欄輸入: http://localhost:8080/

2.運(yùn)行效果分別如下

默認(rèn)為中文語(yǔ)言環(huán)境

Spring Boot Thymeleaf實(shí)現(xiàn)國(guó)際化的方法詳解

切換到英文環(huán)境后,界面效果如下

Spring Boot Thymeleaf實(shí)現(xiàn)國(guó)際化的方法詳解

資料

  • Spring Cloud Feign 示例源碼
  • Spring Boot、Spring Cloud示例學(xué)習(xí)

總結(jié)

以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,謝謝大家對(duì)億速云的支持。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI