thymeleaf使用
先导入依赖
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf</artifactId>
<version>3.0.12.RELEASE</version>
</dependency>
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring4</artifactId>
<version>3.0.12.RELEASE</version>
</dependency>
建议导入spring4的版本,spring5版本可能存在idea爆红的现象(但不影响代码运行)
在springmvc的配置文件中关闭静态资源过滤和jsp的视图解析器
<!--2.静态资源过滤-->
<!--<mvc:default-servlet-handler/>-->
<!--4.视图解析器-->
<!--<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">-->
<!-- <property name="prefix" value="/WEB-INF/jsp/"/>-->
<!-- <property name="suffix" value=".jsp"/>-->
<!--</bean>-->
在springmvc的配置文件中配置thymeleaf的视图解析器
<!--thymeleaf模板引擎解析器-->
<bean id="viewResolver" class="org.thymeleaf.spring4.view.ThymeleafViewResolver">
<property name="order" value="1"/>
<property name="characterEncoding" value="UTF-8"/>
<property name="templateEngine" ref="templateEngine"/>
</bean>
<bean id="templateEngine" class="org.thymeleaf.spring4.SpringTemplateEngine">
<property name="templateResolver" ref="templateResolver" />
</bean>
<bean id="templateResolver" class="org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver">
<property name="prefix" value="/WEB-INF/templates/"/>
<property name="suffix" value=".html"/>
<property name="templateMode" value="HTML5"/>
<property name="characterEncoding" value="UTF-8" />
</bean>
在controller层写一个控制器
@RequestMapping("/user")
public String toUser(Model model){
model.addAttribute("time",new Date());
return "user";
}
在视图解析器所规定的文件夹下创建一个html文件
user.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<p th:text="${#dates.format(time,'yyyy年MM月dd日')}">
</p>
</body>
</html>
最后访问该路径
结果:
thymeleaf语法
使用thymeleaf前必须先加入命名空间,否则不能使用
命名空间 xmlns:th=“http://www.thymeleaf.org”
简单表达式 (simple expressions)
${…} 变量表达式
*{…} 选择变量表达式
#{…} 消息表达式
@{…} 链接url表达式
样例
controller
@Controller
public class IndexController {
@RequestMapping("/test")
public String test(Model model){
model.addAttribute("msg","<h1>hello</h1>");
model.addAttribute("users", Arrays.asList(1,2,3));
return "test";
}
}
html
<div th:text="${msg}"></div>
<!--转义,能把msg中的html标签给转义出来-->
<div th:utext="${msg}"></div>
<!--遍历数据-->
<!--th:each每次遍历都会生成当前这个标签:官网#9-->
<h4 th:each="user :${users}" th:text="${user}"></h4>
结果