springboot 模板 的兩種實現方式

springboot模板的兩種方式


在上一篇的博文中我們以經入門springboot了,在springboot中我們將告別以前我們的寫前端的方式jsp。有的只是HTML和ftl頁面,分別對應兩種模板

Thymeleaf模板

關於Thymeleaf的優點,我只說一條:它就是html頁面。
導入pom依賴:

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

Spring Boot官方文檔建議在開發時將緩存關閉,那就在application.properties文件中加入下面這行

//正式環境還是要將緩存開啓的
spring.thymeleaf.cache=false

對應的後臺代碼

實體類

package com.hu.springboot01.entity;

import lombok.Data;

@Data
public class User {
    private Integer uid;
    private String userName;
    private String password;

    public User(Integer uid, String userName, String password) {
        this.uid = uid;
        this.userName = userName;
        this.password = password;
    }

    public User() {
    }
}

controller層代碼:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>list</title>
</head>
<body>
springboot初步使用thymeleaf


<h2>顯示文本</h2>
<span th:text="${name}"></span>

<hr>
<h2>顯示HTML</h2>
<div th:utext="${msg}"></div>

<hr>
<h2>循環</h2>
<table>
    <tr>
        <td>用戶的ID</td>
        <td>用戶名</td>
        <td>密碼</td>
    </tr>
    <tr th:each="u :${userList}">
        <td th:text="${u.uid}"></td>
        <td th:text="${u.userName}"></td>
        <td th:text="${u.password}"></td>
    </tr>
</table>

<hr style="color: crimson">
<h2>綜合使用</h2>
<li th:each="u : ${userList}">
    <a href="#" th:title="${u.uid }" th:text="${#strings.length(u.userName) < 4 ? u.uid : #strings.substring(u.password, 0, 16)+'...' }">熱點新聞1</a>
</li>

<h2>如何在頁面定義變量</h2>

<div th:include="role/common/head2"></div>

指定導入的東西:
<div th:replace="role/common/head2 :: h3" ></div>

</body>
</html>

head2需要引入的HTML代碼:

<div th:fragment="h1">
    第一部分
</div>
<div th:fragment="h2">
    第二部分
</div>
<div th:fragment="h3">
    第三部分
</div>

前臺代碼:

 <html xmlns:th="http://www.thymeleaf.org">
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>list</title>
</head>
<body>
springboot初步使用thymeleaf


<h2>顯示文本</h2>
<span th:text="${name}"></span>

<hr>
<h2>顯示HTML</h2>
<div th:utext="${msg}"></div>

<hr>
<h2>循環</h2>
<table>
    <tr>
        <td>用戶的ID</td>
        <td>用戶名</td>
        <td>密碼</td>
    </tr>
    <tr th:each="u :${userList}">
        <td th:text="${u.uid}"></td>
        <td th:text="${u.userName}"></td>
        <td th:text="${u.password}"></td>
    </tr>
</table>

<hr style="color: crimson">
<h2>綜合使用</h2>
<li th:each="u : ${userList}">
    <a href="#" th:title="${u.uid }" th:text="${#strings.length(u.userName) < 4 ? u.uid : #strings.substring(u.password, 0, 16)+'...' }">熱點新聞1</a>
</li>

<h2>如何在頁面定義變量</h2>

<div th:include="role/common/head2"></div>

指定導入的東西:
<div th:replace="role/common/head2 :: h3" ></div>

</body>
</html>

效果圖:
在這裏插入圖片描述

html上對字符串的處理

判斷是不是爲空:null: 
<span th:if="${name} != null">不爲空</span> 
<span th:if="${name1} == null">爲空</span> 
判斷是不是爲空字符串: “” 
<span th:if="${#strings.isEmpty(name1)}">空的</span> 
判斷是否相同: 
<span th:if="${name} eq 'jack'">相同於jack,</span> 
<span th:if="${name} eq 'ywj'">相同於ywj,</span> 
<span th:if="${name} ne 'jack'">不相同於jack,</span> 
不存在設置默認值: 
<span th:text="${name2} ?: '默認值'"></span> 
是否包含(分大小寫): 
<span th:if="${#strings.contains(name,'ez')}">包ez</span> 
<span th:if="${#strings.contains(name,'y')}">包j</span> 
是否包含(不分大小寫) 
<span th:if="${#strings.containsIgnoreCase(name,'y')}">包j</span> 
同理。。。下面的和JAVA的String基本一樣。。。。不筆記解釋,官網有

${#strings.startsWith(name,'o')} 
${#strings.endsWith(name, 'o')} 
${#strings.indexOf(name,frag)}// 下標 
${#strings.substring(name,3,5)}// 截取 
${#strings.substringAfter(name,prefix)}// 從 prefix之後的一位開始截取到最後,比如 (ywj,y) = wj, 如果是(abccdefg,c) = cdefg//裏面有2個c,取的是第一個c 
${#strings.substringBefore(name,suffix)}// 同上,不過是往前截取 
${#strings.replace(name,'las','ler')}// 替換 
${#strings.prepend(str,prefix)}// 拼字字符串在str前面 
${#strings.append(str,suffix)}// 和上面相反,接在後面 
${#strings.toUpperCase(name)} 
${#strings.toLowerCase(name)} 
${#strings.trim(str)} 
${#strings.length(str)} 
${#strings.abbreviate(str,10)}// 我的理解是 str截取0-10位,後面的全部用…這個點代替,注意,最小是3位

對日期的格式化

th:text="${#dates.format(news.publishDate, 'yyyy-MM-dd')}"

兩種的模板其實都差不多,小編還是比較喜歡HTML的

Freemarker模板

Freemarker學習網址

導入pom依賴

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



<!--可以不加,但是做項目的時候可能會用-->
 <resources>
   <!--解決mybatis-generator-maven-plugin運行時沒有將XxxMapper.xml文件放入target文件夾的問題-->
      <resource>
          <directory>src/main/java</directory>
          <includes>
              <include>**/*.xml</include>
          </includes>
      </resource>
      <!--freemarker模板也讀取需要註釋標紅地方-->
      <resource>
          <directory>src/main/resources</directory>
          <includes>
              <!--<include>*.properties</include>-->
              <!--<include>*.xml</include>-->
              <!--<include>*.yml</include>-->
          </includes>
      </resource>
  </resources>

application.yml文件的默認配置

spring:
  thymeleaf:
    cache: false
    
  freemarker:
    # 設置模板後綴名
    suffix: .ftl
    # 設置文檔類型
    content-type: text/html
    # 設置頁面編碼格式
    charset: UTF-8
    # 設置頁面緩存
    cache: false
    # 設置ftl文件路徑,默認是/templates,爲演示效果添加role
    template-loader-path: classpath:/templates/role
  mvc:
    static-path-pattern: /static/**

後臺代碼:

role實體類:

package com.hu.springboot01.entity;

import lombok.Data;

/**
 * @author hu
 * @site www.huguiyun.xzy
 * @company xxx公司
 * @create  2019-11-08 18:07
 */
@Data
public class Role {
    private String rid;
    private String rname;

    public Role(){}

    public Role(String rid,String rname){
        this.rid = rid;
        this.rname = rname;
    }

}

Controller代碼:

package com.hu.springboot01.controller;

import com.hu.springboot01.entity.Role;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.List;

/**
 * @author hu
 * @site www.huguiyun.xzy
 * @company xxx公司
 * @create  2019-11-08 18:03
 */
@Controller
@RequestMapping("/freemarker")
public class FreemarkerController {

    @RequestMapping("/list1")
    public ModelAndView list(){
        ModelAndView mv = new ModelAndView();

        mv.addObject("loginName","freemarker簡單使用");
        List list = new ArrayList();
        list.add(new Role("1","簡單"));
        list.add(new Role("2","複雜"));
        list.add(new Role("3","困難"));
        list.add(new Role("4","地獄"));
        list.add(new Role("5","噩夢"));
        mv.addObject("roleList",list);
        mv.addObject("sex","男");
        mv.setViewName("list1");
        return mv;
    }

}

需要導入的代碼:

//global.ftl
<#global ctx>
    ${springMacroRequestContext.contextPath}
</#global>

//head.ftl
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h5>
    我是另外的一個頁面
</h5>
</body>
</html>

前臺代碼:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>freemarker</title>
</head>
<body>
<h2>獲取值</h2>
${loginName ! '未知'}
${logineName ! '未知'}

<h2>遍歷</h2>
<table>
    <tr>
        <td>模式ID</td>
        <td>遊戲模式</td>
    </tr>
    <#list  roleList as role>
    <tr>
        <td>${role.rid}</td>
        <td>${role.rname}</td>
    </tr>
    </#list>
</table>


<h2>包含頁面</h2>
<#include 'common/head.ftl'>
<#include 'common/global.ftl'>

<h2>獲取項目名</h2>
<#assign ctxl>
    ${springMacroRequestContext.contextPath}
</#assign>
${ctxl}

<h2>條件</h2>
<#if sex=='girl'><#elseif sex=='男'><#else>
    保密
</#if>

<h2>如何在頁面定義變量</h2>
${ctx}



</body>
</html>

效果圖:
在這裏插入圖片描述

注意點

  • 1、application.yml中可以配置模板存放位置的根路徑、以及靜態資源文件存放位置的根路徑
  • 2、${springMacroRequestContext.contextPath}:SpringBoot中獲取項目名
  • 3、不推薦使用全局變量。即便它們屬於不同的命名空間, 全局變量也被所有模板共享,因爲它們是被 import進來的。
  • 4、freemarker模板也可以像jsp那樣設置根路徑
<#include 'common.ftl'>
    <script src="js/xxx.js" type="text/javascript"></script>

層級結構:
在這裏插入圖片描述

導入在需要應用的地方添加

<div th:replace="role/common/head :: h3" ></div>

一種是包含整個html頁面

<div th:include="role/common/head"></div>

注意

  • 1、這裏的th:replace裏的路徑是相對於templetes文件夾的。
  • 2、冒號冒號前後都有空格,我沒注意這一點踩了大坑
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章