初识Thymeleaf模板引擎和Webjars

2018-09-08  本文已影响0人  默写_0c03

添加Thymeleaf依赖

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

建立项目结构

resources目录下的static文件夹内放置image,css,js等静态资源
templates下放置Thymeleaf模板页面

目录截图

Controller层代码

package com.niit.controller;

import com.niit.entity.Student;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;

import javax.annotation.Resource;

@Controller
public class IndexController {

    //注入一个student的Bean
    @Resource
    private Student student;

//    @RequestMapping(value = "/index", method = RequestMethod.GET)
    @GetMapping("index")
    public String index(ModelMap map) {
        //使用了lombok依赖
        student.setName("王嘉尔");
        student.setAge(20);
        student.setMale("male");
        student.setStudentNO("2018");

        //将student模型加入视图中
        map.addAttribute("student",student);

        //返回的是页面名(注意这里的页面名与templates下的页面名必须相同)
        return "index";
    }
}

通过Webjars引用资源

什么是Webjars

通过一个引用Bootstrap的例子来操作

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

在templates文件夹下编写页面index.html

注意:
头部需要添加<html>标签&获取数据的方式
引入Bootstrap的地址

<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.css">
</head>
<body>
<h2>来自Thymeleaf模板的内容</h2>
<h2>Hello Thymeleaf~</h2>
<div class="container">
    <div class="alert alert-success">
        <p th:text="${student.name}"></p>
    </div>
</div>
</body>
</html>
上一篇下一篇

猜你喜欢

热点阅读