《springBoot学习篇》(1)集成thymeleaf

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/yqwang75457/article/details/83346623

简介:Thymeleaf是一款用于渲染XML/XHTML/HTML5内容的模板引擎。类似JSP,Velocity,FreeMaker等。

下载:整体项目我已上传打包到百度云盘,解压可用,链接: https://pan.baidu.com/s/18TH54jVMJ-fsB9hPgwzpTg 提取码: nk3j

开工:接下来我将用4个步骤把springBoot与thymeleaf做集成。

第一步:pom.xml引入thymeleaf模块。

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

第二步:application.properties配置thymeleaf。

#thymelea模板配置
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html
spring.thymeleaf.cache=false
spring.resources.chain.strategy.content.enabled=true
spring.resources.chain.strategy.content.paths=/**

第三步:编写模板,放到src/main/resources目录,在这个目录new一个名为templates的Source Floder,然后在templates目录,创建一个index.html模板,最终目录截图如下:

index.html文件,顶部注意“xmlns:th="http://www.thymeleaf.org”:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org">
  <head>
    <title>Spring Boot+thymeleaf Demo</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  </head>

  <body>

    <p th:text="${welcome}">Welcome 等待填充!</p>
    <p th:text="${welcome2}">Welcome2 等待填充!</p>

  </body>

</html>

第四步:controller文件入口ThymeleafCtrl.java。注意controller中一定要是@controller注解,而不是@RestController,这样才能找到页面!!!

package com.wyq.springBoot.ctrl;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/thymeleaf")
public class ThymeleafCtrl {
	//http://127.0.0.1:8080/thymeleaf/index
	@RequestMapping("/index")
	public String index(Model model,HttpServletRequest reqest){
		//传值可以通过model和request
		model.addAttribute("welcome", "欢迎使用Thymeleaf!(model.addAttribute(xxx))");
		reqest.setAttribute("welcome2", "欢迎使用Thymeleaf!(reqest.setAttribute(xxx))");
		return "index";
	}
	
	@RequestMapping(value = "/greeting")
	public ModelAndView test(ModelAndView mv) {
	    mv.addObject("welcome","欢迎使用Thymeleaf!(ModelAndView)");
	    mv.addObject("welcome2","欢迎使用Thymeleaf!(ModelAndView)");
	    mv.setViewName("/index");//
	    return mv;
	}
}

Ok!接下来开始测试了!!!!

启动项目,浏览器输入http://127.0.0.1:8080/thymeleaf/index,效果如下:

扫描二维码关注公众号,回复: 3802361 查看本文章

浏览器输入http://127.0.0.1:8080/thymeleaf/greeting,效果如下:


如果报错或者测试失败,请检查以下几点:

1.pom.xml中引入了对应thymeleaf模块。

2.application.properties中对thymeleaf模板的配置路径。

3.静态模板文件中是否包含<html xmlns="http://www.w3.org/1999/xhtml"  xmlns:th="http://www.thymeleaf.org">。

4.静态模板文件存放位置是否和application.properties中的配置匹配。

猜你喜欢

转载自blog.csdn.net/yqwang75457/article/details/83346623
今日推荐