美文网首页
初识Thymeleaf模板引擎和Webjars

初识Thymeleaf模板引擎和Webjars

作者: 默写_0c03 | 来源:发表于2018-09-08 16:05 被阅读0次

    添加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

    • WebJars能使Maven的依赖管理支持OSS的JavaScript库/CSS库,比如jQuery、Bootstrap等;

    • WebJars是将Web前端Javascript和CSS等资源打包成Java的Jar包,这样在Java Web开发中我们可以借助Maven这些依赖库的管理,保证这些Web资源版本唯一性。

    通过一个引用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>
    

    相关文章

      网友评论

          本文标题:初识Thymeleaf模板引擎和Webjars

          本文链接:https://www.haomeiwen.com/subject/ynokgftx.html