初用Thymeleaf以及與WebJars配合

什么是Thymeleaf

    Thymeleaf的優(yōu)點(diǎn)是它是基于HTML的,即使視圖沒有渲染成功,也是一個(gè)標(biāo)準(zhǔn)的HTML頁面。

前身方法

   前期技術(shù)都是JSP,JSP的優(yōu)點(diǎn)是它是Java EE容器的一部分,幾乎所有Java EE服務(wù)器都支持JSP。缺點(diǎn)就是它在視圖表現(xiàn)方面的功能很少,假如我們想迭代一個(gè)數(shù)組之類的,只能使用<% %>來包括Java語句進(jìn)行。雖然有標(biāo)準(zhǔn)標(biāo)簽庫(JSTL)的補(bǔ)足,但是使用仍然不太方便。另外JSP只能在JavaEE容器中使用,如果我們希望渲染電子郵件之類的,JSP就無能為力了。

配置引入方法

1、添加依賴

        <!--thymeleaf模板引擎依賴-->
        <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

2、Controller寫法

@Controller
public class IndexController {
        //注入一個(gè)student類對象,被spring容器托管---bean
        @Resource
        private Student student;

//    @RequestMapping(value="/index",method = RequestMethod.GET)
    @GetMapping("index")
    public String index(ModelMap map){
        student.setAge(20);
        student.setName("Tom");
        student.setMale("male");
        student.setStudentNo("2018");
        //將模型加入視圖
        map.addAttribute("student",student);
        return "index";//返回值就是頁面名稱
    }
}

3、HTML寫法
頂部添加

<html xmlns:th="http://www.thymeleaf.org">

配合WebJars

1、添加依賴

        <!--引用bootstrap-->
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>bootstrap</artifactId>
            <version>3.3.7-1</version>
        </dependency>

2、網(wǎng)頁代碼

<html xmlns:th="http://www.thymeleaf.org">
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>主頁</title>
    <link rel="stylesheet" href="/webjars/bootstrap/3.3.7-1/css/bootstrap.min.css" />
</head>
<body>
<div class="container">
    <div class="alert alert-success">
        <p th:text="${student.name}"></p>
        <p th:text="${student.age}"></p>
        <p th:text="${student.male}"></p>
    </div>
</div>
</body>
</html>

3、Controller代碼

import javax.annotation.Resource;

/**
 * Created by lenovo on 2018/9/6.
 */
@Controller
public class IndexController {
        //注入一個(gè)student類對象,被spring容器托管---bean
        @Resource
        private Student student;

//    @RequestMapping(value="/index",method = RequestMethod.GET)
    @GetMapping("index")
    public String index(ModelMap map){
        student.setAge(20);
        student.setName("Tom");
        student.setMale("male");
        student.setStudentNo("2018");
        //將模型加入視圖
        map.addAttribute("student",student);
        return "index";//返回值就是頁面名稱
    }
}

Thymeleaf引擎配合WebJars效果圖初樣

效果圖.png
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容