加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

springboot使用thymeleaf

(2022-04-21 17:41:27)
标签:

spring

boot

thymeleaf

分类: java
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 setters
}

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>

0

阅读 收藏 喜欢 打印举报/Report
前一篇:synchronized
后一篇:tool.jar缺少
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有