新浪博客

springboot使用thymeleaf

2022-04-21 17:41阅读:
1.后端 xxx.java
model 参数的 Controller 返回字符串, 表示文件名. thymeleaf 会去寻找 resources/templates/xxx.html 文件, 并带上 model 数据
@Controller
public class TestController {
@RequestMapping(value = 'test', method = RequestMethod.GET)
public String test(Model model) {
model.addAttribute('test', 'hello');
return 'index';
}
}
2.前端 xxx.html
a.字符串
<span th:text='#{test}' />
b.列表
<tbody>
<tr th:each='student: ${students}'>
<td th:text='${student.id}' />
<td th:text='${student.name}' />
</tr>
</tbody>
java 定义如下:
public class Student implements Serializable {
private Integer id;
private String name;
// standard getters and setter
s
}
controller 函数内传递参数:
List<Student> students = new ArrayList<Student>();
// logic to build student data
model.addAttribute('students', students);
c.表单提交
<form action='#' th:action='@{/saveStudent}' th:object='${student}' method='post'>
<table border='1'>
<tr>
<td><label th:text='#{msg.id}' /></td>
<td><input type='number' th:field='*{id}' /></td>
</tr>
<tr>
<td><label th:text='#{msg.name}' /></td>
<td><input type='text' th:field='*{name}' /></td>
</tr>
<tr>
<td><input type='submit' value='Submit' /></td>
</tr>
</table>
</form>
controller 处理
@Controller
public class StudentController {
@RequestMapping(value = '/saveStudent', method = RequestMethod.POST)
public String saveStudent(@ModelAttribute Student student, BindingResult errors, Model model) {
// logic to process input data
}
}
3. js 获取 Model
<script th:inline='javascript'>
var test= [[${test}]];
console.log(test);
</script>

我的更多文章

下载客户端阅读体验更佳

APP专享