Simple introduction to springboot (5-2): front-end interface-thymeleaf template engine

Template engine

SpringBoot recommends using a template engine to render html. If you are not a historical project, you must not use JSP. There are many commonly used template engines, such as freemark, thymeleaf, etc., but they are all the same.
Among them, springboot strongly recommends thymeleaf :

1) Add thymeleaf support for pom file types, and delete JSP support:

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

        <!--&lt;!&ndash;JavaServer Pages Standard Tag Library,JSP标准标签库&ndash;&gt;-->
        <!--<dependency>-->
            <!--<groupId>javax.servlet</groupId>-->
            <!--<artifactId>jstl</artifactId>-->
        <!--</dependency>-->
        <!--&lt;!&ndash;内置tocat对Jsp支持的依赖,用于编译Jsp&ndash;&gt;-->
        <!--<dependency>-->
            <!--<groupId>org.apache.tomcat.embed</groupId>-->
            <!--<artifactId>tomcat-embed-jasper</artifactId>-->
        <!--</dependency>-->

2) Delete the content of the view parser in the application.properties file:

~~#spring.mvc.view.prefix=/WEB-INF/jsp/
#spring.mvc.view.suffix=.jsp~~ 

3) The content of the new Controller is as follows

package cn.enjoy.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/tpl")
public class ThymeleafController {
    
    
    @RequestMapping("/testThymeleaf")
    public String testThymeleaf(ModelMap map) {
    
    
     // 设置属性
     map.addAttribute("name", "enjoy");
     // testThymeleaf:为模板文件的名称
     // 对应src/main/resources/templates/testThymeleaf.html
     return "testThymeleaf";
 }
}

4) The default template configuration path for Springboot is: src/main/resources/templates :
Create a new templates directory in the resources directory, and create a new testThymeleaf.html file in the directory:

<!DOCTYPE html>
<html xmlns:th="http://www.w3.org/1999/xhtml">
<head lang="en">
    <meta charset="UTF-8" />
    <title>enjoy</title>
</head>
<body>
<h1 th:text="${name}"/>
</body>
</html>
	在浏览器上输入:localhost:8080/tpl/testThymeleaf,可以看到页面。

Previous chapter: Simple introduction to springboot (5-1): Front-end interface-Jsp integration

Guess you like

Origin blog.csdn.net/weixin_46822085/article/details/109306645
Recommended