初用Thymeleaf以及与WebJars配合

2018-09-06  本文已影响143人  技术小白熊

什么是Thymeleaf

    Thymeleaf的优点是它是基于HTML的,即使视图没有渲染成功,也是一个标准的HTML页面。

前身方法

   前期技术都是JSP,JSP的优点是它是Java EE容器的一部分,几乎所有Java EE服务器都支持JSP。缺点就是它在视图表现方面的功能很少,假如我们想迭代一个数组之类的,只能使用<% %>来包括Java语句进行。虽然有标准标签库(JSTL)的补足,但是使用仍然不太方便。另外JSP只能在JavaEE容器中使用,如果我们希望渲染电子邮件之类的,JSP就无能为力了。

配置引入方法

1、添加依赖

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

2、Controller写法

@Controller
public class IndexController {
        //注入一个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、网页代码

<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 {
        //注入一个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
上一篇 下一篇

猜你喜欢

热点阅读