Integrate Thymeleaf and internationalize
1. Integrate Thymeleaf
Spring Boot recommends using Thymeleaf as its template engine. SpringBoot provides a series of default configurations for Thymeleaf. Once the dependency of Thymeleaf is imported into the project, the corresponding automatic configuration (Thymeleaf autoconfiguration) will take effect automatically. Therefore, Thymeleaf can be perfectly integrated with Spring Boot.
Spring Boot provides a complete set of automatic configuration scheme for Thymeleaf through Thymeleaf autoconfiguration automatic configuration class. Part of the source code of this automatic configuration class is as follows.
1 @Configuration(proxyBeanMethods = false) 2 @EnableConfigurationProperties({ThymeleafProperties.class}) 3 @ConditionalOnClass({TemplateMode.class, SpringTemplateEngine.class}) 4 @AutoConfigureAfter({WebMvcAutoConfiguration.class, WebFluxAutoConfiguration.class}) 5 public class ThymeleafAutoConfiguration { 6 7 }
ThymeleafAutoConfiguration uses the @ EnableConfigurationProperties annotation to import the ThymeleafProperties class, which contains automatic configuration properties related to Thymeleaf. Part of its source code is as follows.
1 @ConfigurationProperties(prefix = "spring.thymeleaf") 2 public class ThymeleafProperties { 3 private static final Charset DEFAULT_ENCODING; 4 public static final String DEFAULT_PREFIX = "classpath:/templates/"; 5 public static final String DEFAULT_SUFFIX = ".html"; 6 private boolean checkTemplate = true; 7 private boolean checkTemplateLocation = true; 8 private String prefix = "classpath:/templates/"; 9 private String suffix = ".html"; 10 private String mode = "HTML"; 11 private Charset encoding; 12 private boolean cache; 13 14 ... 15 }
ThymeleafProperties prefix the configuration file (application.properties/application.yml) with spring. Through the @ ConfigurationProperties annotation The configuration of thymeleaf is bound to the properties in this class.
The following static variables are also provided in ThymeleafProperties:
DEFAULT_ENCODING: default encoding format
DEFAULT_PREFIX: prefix of the view parser
DEFAULT_SUFFIX: suffix of view parser
Like other custom configurations of Spring Boot, we can properties/application. Modify in YML to spring The attribute prefixed with Thymeleaf to modify the automatic configuration of Thymeleaf by Spring Boot.
Spring Boot integrates Thymeleaf template engine. The following steps are required:
Introduce dependency
Create a template file and put it in the specified directory
1) introduce dependency
Modify POM xml:
1 <project ... > 2 ... 3 <dependencies> 4 ... 5 6 <!-- Thymeleaf --> 7 <dependency> 8 <groupId>org.springframework.boot</groupId> 9 <artifactId>spring-boot-starter-thymeleaf</artifactId> 10 </dependency> 11 12 ... 13 </dependencies> 14 15 ... 16 </project>
In IDE, select project list - > springbootweb - > right click - > Maven - > reload project
2) create template file
According to the configuration properties of Thymeleaf properties, the default location of Thymeleaf template is in the resources/templates directory, and the default suffix is HTML, that is, Thymeleaf can render automatically as long as the HTML page is placed under "classpath:/templates /".
Example, in“ Spring Basics (27) - Spring Boot (8) ”Based on the springboot web project in, it is modified as follows.
(1) create Src / main / resources / templates / common HTML file
1 <div th:fragment="fragment-header" id="fragment-header-id"> 2 <p>Header</p> 3 </div> 4 <div th:fragment="fragment-banner" id="fragment-banner-id"> 5 <p>Banner</p> 6 <hr /> 7 </div> 8 <div th:fragment="fragment-footer" id="fragment-footer-id"> 9 <hr /> 10 <p>Footer</p> 11 </div>
Note: if src/main/resources/templates directory does not exist, manually create directories at all levels, the same below.
(2) create Src / main / resources / templates / demo HTML file
1 <!DOCTYPE html> 2 <html lang="en" xmlns:th="http://www.thymeleaf.org"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Demo</title> 6 </head> 7 <body> 8 9 <div th:replace="common::fragment-header"></div> 10 11 <div th:include="common::fragment-banner"></div> 12 13 <div id="content"> 14 15 <h3 th:text="'Welcome ' + ${name}">Welcome</h3> 16 17 <div th:object="${user}" > 18 <p th:text="*{firstName}">firstName</p> 19 </div> 20 21 <div th:insert="common::fragment-footer"></div> 22 23 </body> 24 </html>
(3) create Src / main / Java / COM / example / entity / user Java file
1 package com.example.entity; 2 3 import org.springframework.stereotype.Component; 4 import org.springframework.boot.context.properties.ConfigurationProperties; 5 6 @Component 7 @ConfigurationProperties(prefix = "user") 8 public class User { 9 private String firstName; 10 private Integer age; 11 12 public User() { 13 14 } 15 16 public String getFirstName() { 17 return firstName; 18 } 19 public void setFirstName(String firstName) { 20 this.firstName = firstName; 21 } 22 23 public Integer getAge() { 24 return age; 25 } 26 public void setAge(Integer age) { 27 this.age = age; 28 } 29 @Override 30 public String toString() { 31 return "User {" + 32 "firstName = " + firstName + 33 ", age = " + age + 34 '}'; 35 } 36 }
(4) create Src / main / Java / COM / example / controller / indexcontroller Java file
1 package com.example.controller; 2 3 import java.util.Map; 4 import org.springframework.stereotype.Controller; 5 import org.springframework.web.bind.annotation.RequestMapping; 6 7 import com.example.entity.User; 8 9 @Controller 10 public class IndexController { 11 @Autowired 12 User user; 13 14 @RequestMapping("/demo") 15 public String demo(Map<String, Object> map) { 16 17 user.setFirstName("Tester"); 18 user.setAge(21); 19 20 map.put("name", "admin"); 21 map.put("user", user); 22 return "demo"; 23 } 24 }
Visit http://localhost:9090/demo , the page displays:
Header
Banner
----------------------
Welcome admin
Tester
-----------------------
Footer
2. Internationalization
Internationalization (I18n for short, where "I" and "n" are the first and last characters respectively, and 18 is the number of characters in the middle) refers to the function of supporting multiple languages and regions during software development.
In other words, the developed software needs to be able to respond to user visits from different countries and regions at the same time, and provide corresponding pages and data in line with the reading habits of appliances according to the user's region and language habits. For example, it provides Chinese interface display for Chinese users and English interface display for American users.
To implement internationalization in Spring projects, you usually need the following steps:
(1) prepare international resource (configuration) documents;
(2) use ResourceBundleMessageSource to manage international resource files;
(3) get international content on the page;
1) prepare international resource documents
Create a directory of i18n under src/main/resources, and create the following three files in this directory according to the naming format of international resource files:
login.properties: takes effect when there is no language setting
login_en_US.properties: effective in English
login_zh_CN.properties: effective in Chinese
After the above internationalization resource files are created, the IDEA will automatically identify them and convert them to Resource Bundle mode.
Open login Properties, click the Resource Bundle tab at the bottom of the window, and then click the "+" sign to create the Username and Password properties.
Modified login Properties file
login.title=Login(default)
login.password=Password(default)
login.username=Username(default)
Modified login_en_US.properties file
login.title=Login
login.password=Password
login.username=Username
Modified login_zh_CN.properties file
login.title = login
login.password = password
login.username = username
2) use ResourceBundleMessageSource to manage international resource files
Spring Boot has provided default automatic configuration for the management of international resource files. We only need to use the configuration parameter "spring.messages.basename" in the Spring Boot global configuration file to specify the basic name of our customized international resource files. When specifying multiple resource files, use commas to separate them.
Modify Src / main / resources / application Properties file, add the following content:
spring.messages.basename=i18n.login
spring.messages.encoding=UTF-8
Note: Spring Boot automatically selects resource files according to the accept language of the request header released by the browser. For example, accept language: zh cn is mapped to login_zh_CN.properties, accept language: mapping en US to login_en_US.properties, other values will be mapped to login by default properties.
3) get international content on the page
The page uses Tymeleaf template, which can be expressed by #{...} Get international content, such as:
<p th:text="#{login.username}">Username</p>
For example, based on the above springboot web project, the code is as follows.
(1) create Src / main / resources / templates / login HTML file
1 <!DOCTYPE html> 2 <html lang="en" xmlns:th="http://www.thymeleaf.org"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Login</title> 6 </head> 7 <body> 8 9 <h3 th:text="#{login.title}">Login</h3> 10 11 <p><span th:text="#{login.username}">Username</span>: 12 <input type="text" name="username" value="" /></p> 13 <p><span th:text="#{login.password}">Password</span>: 14 <input type="text" name="password" value="" /></p> 15 16 </body> 17 </html>
(2) create Src / main / Java / COM / example / controller / usercontroller Java file
1 package com.example.controller; 2 3 import org.springframework.stereotype.Controller; 4 import org.springframework.web.bind.annotation.RequestMapping; 5 6 @Controller 7 @RequestMapping("/user") 8 public class UserController { 9 @RequestMapping("/login") 10 public String login() { 11 return "login"; 12 } 13 }
Visit http://localhost:9090/user/login , the Chinese browser will display:
Login
User name:
Password: