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>