【Springboot采坑日记】Springboot+thymeleaf集成i18n过程及注意事项
Springboot+thymeleaf+i18n的配置方式
thymeleaf集成
导入thymeleaf依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
<version>2.3.3.RELEASE</version>
</dependency>
配置thymeleaf的yml文件
spring:
thymeleaf:
cache: false # 将thymeleaf缓存关闭
encoding: UTF-8
然后就可以将值传入model中,由前端html直接展示
Controller:
@Controller
public class TestController {
@RequestMapping("test")
public String indexHandler(Model model, HttpServletRequest request, HttpSession session){
model.addAttribute("welcome","hello world");
model.addAttribute("student",new Test("zhangsan",80));
model.addAttribute("gender","male");
List<Test> students = new ArrayList<>();
students.add(new Test("张三",13));
students.add(new Test("李四",25));
students.add(new Test("赵三",60));
model.addAttribute("students",students);
Map<String,Object> map = new HashMap<>();
map.put("stu7",new Test("田七",27));
map.put("stu8",new Test("刘八",28));
map.put("stu9",new Test("郑九",29));
model.addAttribute("map",map);
model.addAttribute("attrName","score");
model.addAttribute("attrValue",99);
model.addAttribute("welcome1","<h2>Thymeleaf,<br>I'm learning.</h2>");
model.addAttribute("photo","email.png");
model.addAttribute("elementId","reddiv");
model.addAttribute("bgColor","red");
model.addAttribute("isClose",false);
model.addAttribute("school",null);
List<String> cities = new ArrayList<>();
model.addAttribute("cities",cities);
request.setAttribute("req","reqValue");
session.setAttribute("ses","sesValue");
session.getServletContext().setAttribute("app","appValue");
int[] nums = {
1,2,3,4,5,6};
model.addAttribute("nums",nums);
model.addAttribute("today",new Date());
model.addAttribute("cardId","684515202008258475");
//这里test表示thymeleaf所对应的test.html,不用写扩展名
return "test";
}
}
HTML
<!DOCTYPE html>
<html lang="en" xmlns:th="https://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Hello world</title>
</head>
<!--请求路径:http://localhost:8888/test?name=zhangsan-->
<body>
<!--展示文本 类似jsp ${}-->
<p th:text="${welcome}">这里将显示数据,但这些文字不显示</p>
<div th:text="${welcome}">这里将显示数据,但这些文字不显示</div>
<span th:text="${welcome}">这里将显示数据,但这些文字不显示</span>
<hr>
<!--展示类-->
<p th:text="${student}" id="student">aaaa</p>
<p th:text="${student.name}">vvvv</p>
<p th:text="${student.age}"