springboot2.0 集成thymeleaf

thymeleaf 是按照严格的html格式来执行的,我们平时用的html不是那么严格。因此需要配置成不是很严格的,

#前缀,也就是模板存放的路径
spring.thymeleaf.prefix=classpath:/web/
#编码格式
spring.thymeleaf.encoding=UTF-8
#是否开启缓存
spring.thymeleaf.cache=false
#后缀
spring.thymeleaf.suffix=.html
#设置不严格的html
spring.thymeleaf.mode=LEGACYHTML5

并且添加依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
    <groupId>net.sourceforge.ntkohtml</groupId>
    <artifactId>ntkohtml</artifactId>
    <version>1.9.22</version>
</dependency>

且不要低于1.9.15

在html页面获取controller 传来的mode;

Controller:

package com.springboot2.thyemleaf.controller;

import com.springboot2.thyemleaf.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by  lpw'ASUS on 2018/5/28.
 */
@Controller
@RequestMapping("/thyemleaf")
public class ThymeleafController {

    @RequestMapping("demo")
    public String testthymeleaf(Model model)throws Exception{
        model.addAttribute("str","hello springboot2.0 -thymeleaf");
        User user = new User("张三",23);
        User user1 = new User("王五",46);
        model.addAttribute("user",user);
        List<User> list=new ArrayList<User>();
        list.add(user);
        list.add(user1);
        model.addAttribute("list",list);
        System.out.print(2525);
        System.out.print(5212);

        model.addAttribute("imgsrc","/img/1.jpg");
        if(true){
            throw new Exception("非运行时异常");
        }
        return "template";
    }
}

htmly页面:一般都是在原来的属性前面加th:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>thymeleaf 模板</h1>
    <span th:text="${str}"></span>
    <hr/>
    name:<span th:text="${user.name}"></span><br/>
    age:<span th:text="${user.age}"></span>
    <hr/>
    <h3>循环主题加内容</h3>
    <div th:each="l:${list}">
        <span th:text="${l.name}"></span>
        <span th:text="${l.age}"></span>
    </div>
    <h3>下拉列表</h3>
    <select >
        <option th:each="l:${list}" th:value="${l.age}" th:text="${l.name}" th:selected="${l.age==46}"> </option>
    </select>

    <h3 > 图片</h3>
    <img th:src="${imgsrc}"/>


</body>
</html>

当html中th:报错或没有提示时,因为没有引入th标签,但不影响使用,只需要在html标签中添加以下内容即可

<html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">


猜你喜欢

转载自blog.csdn.net/m0_38044453/article/details/80470946