springBoot(5):web開發-模板引擎FreeMarker與thymeleaf

1、簡介javascript

spring boot的web應用開發,是基於spring mvc。css


Spring boot在spring默認基礎上,自動配置添加了如下特性:html

 一、包含了ContentNegotiatingViewResolver和BeanNameViewResolver beans。java

 二、對靜態資源的支持,包括對WebJars的支持。jquery

 三、自動註冊Converter,GenericConverter,Formatter beans。linux

 四、對HttpMessageConverters的支持。web

 五、自動註冊MessageCodeResolver。spring

 六、對靜態index.html的支持。數組

 七、對自定義Favicon的支持。瀏覽器

 八、主動使用ConfigurableWebBindingInitializer bean


2、模板引擎的選擇

FreeMarker

Thymeleaf

Velocity (1.4版本以後棄用,Spring Framework 4.3版本以後棄用)

Groovy

Mustache

注:jsp應該儘可能避免使用,緣由以下:

 一、jsp只能打包爲:war格式,不支持jar格式,只能在標準的容器裏面跑(tomcat,jetty均可以)

 二、內嵌的Jetty目前不支持JSPs

 三、Undertow不支持jsps

 四、jsp自定義錯誤頁面不能覆蓋spring boot 默認的錯誤頁面

3、FreeMarker使用

新建一個工程,勾選Freemarker、DevTools(開發方便)

wKioL1k_azHgXoASAABPQCG3DAQ480.jpg

會自動在pom.xml中加入Freemarker的配置:

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


WebController.java:

package com.example.demo.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * Created by DELL on 2017/6/13.
 */
@Controller
@RequestMapping("/web")
public class WebController {
    private static final Logger logger = LoggerFactory.getLogger(WebController.class);

    @RequestMapping("/index")
    public String index(Model model){
        logger.info("這是一個controller");
        model.addAttribute("title","我是一個例子");
        return "index";  // 注意,不要再最前面加上/,linux下面會出錯
    }
}

index.ftl:

<!DOCTYPE html>
<html>
<head lang="en">
   <title>Spring Boot Demo - FreeMarker</title>
    <link href="/css/index.css" rel="stylesheet" />
</head>
<body>
    <center>
        <img src="/images/logo.png" />
        <h1 id="title">${title}</h1>
    </center>

    <script type="text/javascript" src="/js/jquery.min.js"></script>

    <script>
        $(function(){
            $('#title').click(function(){
                alert('點擊了');
            });
        })
    </script>
</body>
</html>


說明:

 一、視圖默認訪問templates下面,如"index",則:在templates下面找index.ftl

 二、css、js、img等靜態資源則在static下面找,如<link href="/css/index.css" rel="stylesheet" />,則是找static下面的css下面的index.css文件

4、thymeleaf模塊

4.一、簡介

Thymeleaf是一個優秀的面向java的XML/XHTML/HTML5頁面模板,而且有豐富的標籤語言和函數。使用Springboot框架進行界面設計,通常都會選擇Thymeleaf模板。

4.二、使用

引入依賴:

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


配置application.properties文件:

#####################thymeleaf開始#####################################
#關閉緩存
spring.thymeleaf.cache=false
#後綴
spring.thymeleaf.suffix=.html
#編碼
spring.thymeleaf.encoding=UTF-8
#####################thymeleaf結束#####################################

IndexController.java:

@Controller
public class IndexController {
    @RequestMapping("/index")
    public String show(Model model) throws Exception {
        List<User> users = new ArrayList<User>();
        users.add(new User(1L, "zhangsan"));
        users.add(new User(2L, "lisi"));
        users.add(new User(3L, "wangwu"));
        model.addAttribute("hello","我只是一個例子");
        model.addAttribute("users", users);
        model.addAttribute("addtime",new Date());
        return"/helloHtml";
    }
}

main/resources/templates/helloHtml.html:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Hello World!</title>
</head><p th:text="${hello}"></p>
<body>
<h1 th:inline="text">Hello.v.2</h1>
<p th:text="${addtime} ? ${#dates.format(addtime, 'yyyy-MM-dd HH:mm:ss')}"></p>
<select>
    <option>請選擇用戶</option>
    <option th:each="user:${users}" th:value="${user.id}" th:text="${user.name}">
    </option>
</select>
</body>
</html>

瀏覽器中輸入:http://localhost:8989/index ,效果以下:

wKiom1lZt7eSY8JCAABh1wZjjsw709.jpg

4.三、thymeleaf功能簡介

在html頁面中使用thymeleaf標籤語言,用一個簡單的關鍵字「th」來標註,如:

<p th:text="${hello}"></p>
<img th:src="@{images/logo.png}" />

其中th:text指定在<p>標籤中顯示的文本,它的值來自"$"所引用的內存變量。

th:src指定img的圖片地址


注意:使用th,須要<html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">

 wKiom1lcTuSxynbNAABWnFxuX6Y558.jpg


thymeleaf的主要標籤和函數:

th:text,顯示文本。
th:utext,和th:text的區別是針對"unescaped text"。
th:attr,設置標籤屬性
th:if or th:unless,條件判斷語句
th:switch, th:case,選擇語句
th:each,循環語句

#date:日期函數
#calendars:日曆函數
#numbers:數字函數
#strings:字符串函數
#objects:對象函數
#bools:邏輯函數
#arrays:數組函數
#lists:列表函數

詳細標籤請查看官方:http://www.thymeleaf.org/  

相關文章
相關標籤/搜索