SpringBoot use thymeleaf template

How SpringBoot development WEB project Contrller jump to the front page

Spring currently has no official recommended to use JSP to develop the WEB, but is recommended to use a template engine to develop the following categories:

  • Thymeleaf (Spring official recommended)
  • FreeMarker
  • Velocity
  • Groovy
  • Mustache

It is said, the most popular of the two or FreeMarker and Velocity template, we recommend here with Spring official Thymeleaf template

On the basis of the project created SpringBoot, as follows:

  1. In dependence to the POM Thymeleaf

    <!--对HTML的依赖-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    
  2. Set templates to find the path in the application.properties

    # 模板引擎读取路径
    # 是让controller层到templates文件夹寻找xx.html(src/main/resources/templates)
    spring.thymeleaf.prefix=classpath:/templates/
    
  3. Create a html page in the resource / templates directory, such as index.html

    <!DOCTYPE html>
    <html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
        在SpringBoot项目中使用HTML页面<br>
        获取页面上传过来的参数PPP:<p th:text="${param1}"></p>
    </body>
    </html>
    
  4. Create a Controller class

    @Controller
    //  这里不能是RestController注解,不然会输出index字符串
    public class HelloWorld {        
        @RequestMapping("/toIndexPage")
        public String getHtmlPage(HashMap<String, Object> map){
            map.put("param1", "hello world");
            return "index"; // 这里的字符串对应html的文件名(不包含后缀)
        }       
    }
    
  5. Access project

    http://localhost:8080/toIndexPage        

Guess you like

Origin www.cnblogs.com/baimeishaoxia/p/11810362.html