spring boot thymeleaf简单示例

说实话,用起来很难受,但是人家官方推荐,咱得学

如果打成jar,这个就合适了,jsp需要容器支持

引入依赖

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

application.properties中配置

#指定模板所在的目录
spring.thymeleaf.prefix=/WEB-INF/ui/
#检查模板路径是否存在
spring.thymeleaf.check-template-location=true
#如果开启,本地调式页面不会立马更新,上线再打开缓存提高性能
spring.thymeleaf.cache=false
#模板文件后缀
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html

thymeleaf建的视图是HTML文件

新建一个testThymeleaf.html,这里简单使用几个属性,详细见手册

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8"></meta>
        <title>thymeleaf test</title>
    </head>
    <body>
        <!-- text展示后台变量 -->
        <h1 th:text="${message }">thymeleaf test</h1>
        <!-- 字符串拼接,用|变量、文本| -->
        <p th:text="|${message },welcome.|"></p>
        <!-- 条件判断,if和unless 条件一致,情况不同显示不同的文本  -->
        <span th:if="${aaa == 'aaa'}" th:text="uuuuuuuuuu"></span>
        <span th:unless="${aaa == 'aaa'}" th:text="ggggggggggggggg"></span>
        <!-- 循环迭代数据 -->
        <table>
            <tr>
                <td>No.</td>
                <td>姓名</td>
                <td>日期</td>
            </tr>
            <tr th:each="each,iterStat : ${users}">
                <td th:text="${iterStat.count}"></td>
                <td>
                    <!-- 链接引用页面变量 -->
                    <a th:text="${each.name}" th:href="@{'/a/'+${each.name}+'/'+${iterStat.count}}">link</a>
                </td>
                <td th:text="${#dates.format(each.date, 'yyyy-MM-dd HH:mm:ss')}"></td>
            </tr>
        </table>
        <a th:href="@{/a/hh/12}">test href</a>
    </body>
</html>

后台示例

@Controller
public class TestThymeleafController {

    @GetMapping("/forward")
    public String forward(ModelMap model){
        model.addAttribute("message", "hello");
        model.addAttribute("aaa", "aaac");
        //直接写HTML文件的名字
        return "testThymeleaf";
    }
    
    @GetMapping("/user")
    public String getUser(ModelMap model){
        List<TestVO> users = new ArrayList<TestVO>();
        TestVO vo = new TestVO();
        vo.setName("小王");
        vo.setDate(new Date());
        users.add(vo);
        model.addAttribute("users", users);
        //直接写HTML文件的名字
        return "testThymeleaf";
    }
    
    @RequestMapping("/a/{p}/{v}")
    @ResponseBody
    public String a(@PathVariable("p") String p,@PathVariable("v") Integer v) {
        return "test href:"+p+v;
    }
}

猜你喜欢

转载自www.cnblogs.com/ixixi/p/11691916.html