Spring Boot Thymeleaf实现国际化的方法详解

 更新时间:2019年10月01日 08:34:01   作者:云天  
这篇文章主要给大家介绍了关于Spring Boot Thymeleaf实现国际化的相关资料,文中通过示例代码介绍的非常详细,对大家学习或者使用Spring Boot具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧

前言

开发传统Java WEB工程时,我们可以使用JSP页面模板语言,但是在SpringBoot中已经不推荐使用了。SpringBoot支持如下页面模板语言

  • Thymeleaf
  • FreeMarker
  • Velocity
  • Groovy
  • JSP

上面并没有列举所有SpringBoot支持的页面模板技术。其中Thymeleaf是SpringBoot官方所推荐使用的,下面来谈谈Thymeleaf实现应用国际化方法。

ps:当然现在开发基本上是前后端分离了,但是难免需要维护遗留项目或没有条件前后端分离的团队还是有很多的,这时候学会必要的前端技能,能达到事半功倍的效果。

添加Thymeleaf依赖

要想使用Thhymeleaf,首先要在pom.xml文件中单独添加Thymeleaf依赖。

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

Spring Boot默认存放模板页面的路径在src/main/resources/templates或者src/main/view/templates,这个无论是使用什么模板语言都一样,当然默认路径是可以自定义的,不过一般不推荐这样做。另外Thymeleaf默认的页面文件后缀是.html

什么是国际化

国际化(internationalization)是设计和制造容易适应不同区域要求的产品的一种方式。它要求从产品中抽离所有地域语言,国家/地区和文化相关的元素。换言之,应用程序的功能和代码设计考虑在不同地区运行的需要,其代码简化了不同本地版本的生产。开发这样的程序的过程,就称为国际化。

Spring Boot Thymeleaf 代码实现国际化

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.静态页面代码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}">英语</a>
    </div>
   </li>
  </ul>
 </div>
</nav>

<div class="container" style="margin-top:50px">

 <div class="jumbotron jumbotron-fluid">
  <div class="container">
   <h1 class="display-4" th:text="#{text.home.message}">Fluid jumbotron</h1>
   <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.语言配置文件

中文简体语言配置文件messages.properties

text.title=国际化示例
text.home=首页
text.language=语言
text.language.chinese=中文(简体)
text.language.english=英语
text.home.message=你好,欢迎你
text.description=这是个国际化模板示例

英文语言配置文件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.h2database</groupId>
   <artifactId>h2</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>

运行示例

1.找到TemplateThymeleafApplication.java文件运行示例

地址栏输入: http://localhost:8080/

2.运行效果分别如下

默认为中文语言环境

切换到英文环境后,界面效果如下

资料

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对脚本之家的支持。

相关文章

  • 解决@Cacheable在同一个类中方法调用不起作用的问题

    解决@Cacheable在同一个类中方法调用不起作用的问题

    这篇文章主要介绍了解决@Cacheable在同一个类中方法调用不起作用的问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-07-07
  • SpringBoot如何实现防盗链

    SpringBoot如何实现防盗链

    这篇文章主要为大家详细介绍了SpringBoot是如何实现防盗链的,文中的示例代码讲解详细,具有一定的借鉴价值,感兴趣的小伙伴可以跟随小编一起学习一下
    2024-12-12
  • Intellij IDEA基于Springboot的远程调试(图文)

    Intellij IDEA基于Springboot的远程调试(图文)

    这篇文章主要介绍了Intellij IDEA基于Springboot的远程调试(图文),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-10-10
  • Java详解多线程协作作业之信号同步

    Java详解多线程协作作业之信号同步

    信号量同步是指在不同线程之间,通过传递同步信号量来协调线程执行的先后次序。CountDownLatch是基于时间维度的Semaphore则是基于信号维度的
    2022-05-05
  • Java简单工厂模式详细解释

    Java简单工厂模式详细解释

    本文主要介绍了JAVA简单工厂模式(从现实生活角度理解代码原理)的相关知识。具有很好的参考价值。下面跟着小编一起来看下吧
    2021-11-11
  • mybatis的MappedStatement线程安全探究

    mybatis的MappedStatement线程安全探究

    这篇文章主要为大家介绍了mybatis的MappedStatement线程安全示例探究,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-08-08
  • Java中try catch 的基本用法示例

    Java中try catch 的基本用法示例

    这篇文章主要给大家介绍了关于Java中try catch 的基本用法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2021-01-01
  • Java面试之线程通讯方式详解

    Java面试之线程通讯方式详解

    线程通信是指多个线程之间通过某种机制进行协调和交互,那为什么一个线程等待和通知机制就需要这么多的实现方式呢?别着急,下面小编来和大家仔细聊聊
    2023-08-08
  • spring boot自定义配置时在yml文件输入有提示问题及解决方案

    spring boot自定义配置时在yml文件输入有提示问题及解决方案

    自定义一个配置类,然后在yml文件具体配置值时,一般不会有提示,今天小编给大家分享spring boot自定义配置时在yml文件输入有提示问题,感兴趣的朋友一起看看吧
    2023-10-10
  • Jmeter生成UUID作为唯一标识符过程图解

    Jmeter生成UUID作为唯一标识符过程图解

    这篇文章主要介绍了Jmeter生成UUID作为唯一标识符过程图解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-08-08

最新评论