1、使用IDEA创建SpringBoot项目

解决SpringBoot项目中Thymeleaf模板的中文乱码问题-LMLPHP

解决SpringBoot项目中Thymeleaf模板的中文乱码问题-LMLPHP

解决SpringBoot项目中Thymeleaf模板的中文乱码问题-LMLPHP

解决SpringBoot项目中Thymeleaf模板的中文乱码问题-LMLPHP

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan; @ComponentScan(basePackages="com.example")
@SpringBootApplication
public class DemoApplication { public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
} }

这里通过@ComponentScan(basePackages="com.example")来扫描包。

package com.example.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; @RestController
public class HelloController { @RequestMapping("/hello")
public String index(){
return "Hello Spring Boot^^^";
} }

2、导入Thymeleaf依赖

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

3、读取properties文件

# application.properties
server.port=8080
server.servlet.context-path=/demo
spring.thymeleaf.cache=false
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.check-template-location=true
spring.thymeleaf.suffix=.html
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.mode=HTML
spring.messages.basename=i18/home

解决SpringBoot项目中Thymeleaf模板的中文乱码问题-LMLPHP

# home.properties、home_zh_CN.properties
welcome=欢迎您!
# home_en_US.properties
welcome=Welcome!
package com.example.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView; @Controller
public class HelloController { @RequestMapping("/goToViewPage")
public ModelAndView passParametersWithModelAndView() {
ModelAndView modelAndView = new ModelAndView("viewPage");
modelAndView.addObject("message", "Baeldung");
return modelAndView;
} }
<!-- viewPage.html -->
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Thymeleaf测试</title>
</head>
<body>
<P th:text="#{welcome}"></P>
</body>
</html>

注意:properties文件的编码格式必须是UTF-8

解决SpringBoot项目中Thymeleaf模板的中文乱码问题-LMLPHP

解决SpringBoot项目中Thymeleaf模板的中文乱码问题-LMLPHP

05-04 11:15