170703、springboot編程之模板使用(thymeleaf、freemarker)


官方不推薦集成jsp,關於使用jsp模板我這里就不贅述,如果有需要的,請自行百度!

thymeleaf的使用

1、在pom中增加thymeleaf支持

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

注:Thymeleaf默認是有緩存的,當然不是我們需要的,在配置文件中可以關閉緩存

2、application.properties配置

####thymeleaf模板使用
##關閉thymeleaf緩存
spring.thymeleaf.cache=false

3、編寫模板文件helloHtml.html

首先在resources文件下創建templates,然后在templates創建helloHtml.html文件

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<title>Hello World!</title>
</head>
<body>
<h1 th:inline="text">Hello World!</h1>
<p th:text="${hello}"></p>
</body>
</html>

4、編寫TemplateController.java控制器類

package com.rick.apps.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Map;

/**
 * Desc :  模板測試
 * User : RICK
 * Time : 2017/8/22 13:33
  */
@Controller
public class TemplateController {
    /**
     * 返回html模板.
     */
    @RequestMapping("/helloHtml")
    public String helloHtml(Map<String,Object> map){
        map.put("hello","Hello Spring Boot");
        return"/helloHtml";
    }
}

5、啟動項目,訪問http://localhost:8080/helloHtml

 

使用freemarker

1、在pom中增加freemarker支持

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

2、編寫TemplateController.java控制器類

 /**
     * 返回freemarker html模板.
     */
    @RequestMapping("/helloFtl")
    public String helloFtl(Map<String,Object> map){
        map.put("hello","Hello freemarker");
        return"/helloFtl";
    }

3、創建helloFtl.ftl

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
    <title>Hello World!</title>
</head>
<body>
<h1>Hello World!</h1>
<p>${hello}</p>
</body>
</html>

4、啟動訪問http://localhost:8080/helloFtl

另外需要注意的是:thymeleaf和freemarker是可以同時存在的!

項目清單:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM