Springboot集成thymeleaf

来源:互联网 发布:spss统计软件 编辑:程序博客网 时间:2024/06/03 21:27

1、Thymeleaf介绍:

Thymeleaf是一个XML/XHTML/HTML5模板引擎,可用于Web与非Web环境中的应用开发。类似于Freemarker,但网友测评说性能极差,优点是前后端可以分别开发,能展示静态或动态页面,能完全替代JSP。为什么在采用Thymeleaf呢?其一,JSP中的JSTL标签库默认的是web2.5,如果要用新的JDK和web3.0+,就不能使用JSTL标签,其二,采用Thymeleaf可以进行前后端分离开发,因为它可以像html一样在浏览器中打开而无需依赖容器,jsp是需要在tomcat之类的容器中启动才可以运行。

2、添加Maven依赖:

<!-- 采用thymeleaf替代JSP,因为web3.0下用jstl标签会有问题 -->

<dependency>

    <groupId>org.springframework.boot</groupId>

    <artifactId>spring-boot-starter-thymeleaf</artifactId>

</dependency>

 

3、application.yml增加配置:

spring:  thymeleaf:    prefix: /templates/    suffix: .html    mode: HTML5    encoding: UTF-8    content-type: text/html    cache: false  # 设置缓存,默认为true,如果为true,每次修改模板后都需要重启服务器才能生效  

4、创建一个UserController.java类:

package com.demo.controller;import java.util.ArrayList;import java.util.List;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.autoconfigure.EnableAutoConfiguration;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.servlet.ModelAndView;import com.demo.entity.User;@Controller@EnableAutoConfiguration@RequestMapping("/user")public class UserController {@RequestMapping("/index")public ModelAndView index(ModelAndView mv) {List datas = new ArrayList();User user1 = new User();user1.setId(1);user1.setName("张三");User user2 = new User();user2.setId(1);user2.setName("张三");datas.add(user1);datas.add(user2);mv.addObject("datas", datas);mv.setViewName("user");return mv;}}

5、在templates下创建user.html:

 ##############配置thymeleaf(在eclipse中开发语法提示需要安装插件) ############

# 插件地址[http://www.thymeleaf.org/eclipse-plugin-update-site/],安装方法:点击eclipse-->help-->Install New Software在弹出的页面中“Work With”框中输入该URL,按回车,等下方加载出来后选中然后点next安装即可。

                Hello World!                

Hello.v.2


6、启动服务器,在浏览器输入http://localhost:8080/user/index观察效果

注意:当项目中同时使用jsp及thymeleaf配置,系统默认采用thymeleaf,jsp配置失效,估计是springboot的优先机制。
上面指的是类似这样的jsp配置:
#指向jsp文件位置:src/main/webapp/pages
spring.mvc.view.prefix:/pages/
# 配置jsp文件的后缀
spring.mvc.view.suffix:.jsp