Spring Boot Thymeleaf 實現國際化

開發傳統Java WEB工程時,咱們可使用JSP頁面模板語言,可是在SpringBoot中已經不推薦使用了。SpringBoot支持以下頁面模板語言php

  • Thymeleaf
  • FreeMarker
  • Velocity
  • Groovy
  • JSP

上面並無列舉全部SpringBoot支持的頁面模板技術。其中Thymeleaf是SpringBoot官方所推薦使用的,下面來談談Thymeleaf實現應用國際化方法。css

ps:固然如今開發基本上是先後端分離了,可是不免須要維護遺留項目或沒有條件先後端分離的團隊仍是有不少的,這時候學會必要的前端技能,能達到事半功倍的效果。
複製代碼

添加Thymeleaf依賴

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

<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)是設計和製造容易適應不一樣區域要求的產品的一種方式。它要求從產品中抽離全部地域語言,國家/地區和文化相關的元素。換言之,應用程序的功能和代碼設計考慮在不一樣地區運行的須要,其代碼簡化了不一樣本地版本的生產。開發這樣的程序的過程,就稱爲國際化。java

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.propertiesjquery

text.title=國際化示例
text.home=首頁
text.language=語言
text.language.chinese=中文(簡體)
text.language.english=英語
text.home.message=你好,歡迎你
text.description=這是個國際化模板示例
複製代碼

英文語言配置文件messages.propertiesgit

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/github

2.運行效果分別以下

默認爲中文語言環境web

切換到英文環境後,界面效果以下spring

資料

相關文章
相關標籤/搜索