springboot集成thymeleaf

整个架构

UserTemplateController

package com.example.demo.controller;

import com.example.demo.entity.UserEntity;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Controller
public class UserTemplateController {
    @Autowired
    private UserService userService;
    @RequestMapping("/templateList")
    public String hello(Model model) {
        System.out.println(userService.findById(1));
        model.addAttribute("message", userService.findById(1));
        return "index";
    }
}

templates/index.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org/">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link th:href="@{/css/bootstrap.min.css}" rel="stylesheet">
    <script th:src="@{/js/jquery.js}"></script>
    <script th:src="@{/js/bootstrap.bundle.min.js}"></script>
</head>
<body>
<!-- 使用th:text属性输出 -->
    <div><label>id:</label><span th:text="${message.id}"></span></div>
    <div><label>姓名:</label><span th:text="${message.name}"></span></div>
    <div><label>年龄:</label><span th:text="${message.age}"></span></div>
    <div><label>描述:</label><span th:text="${message.desc}"></span></div>
    <button type="button" class="btn btn-primary" th:onclick="'getName('+${message.id}+')'">获取当前对象</button>
    <script th:inline="javascript">
        var single = [[${message}]];
        console.log(single);
        function getName(name) {
            console.log(name);
        }
    </script>
</body>
</html>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容