Springboot之Thymeleaf 表单提交

@RequestMapping("/index")
public String index(ModelMap map){
    //单个数据
    map.put("username", "入门案例");

    UserForm user = new UserForm();
    user.setPassword("test_ps");
    user.setUsername("test");

    map.put("userInfo", user);
    return "admin/index";
}

通过${}和*{}的方式来读取表单类对象

<!DOCTYPE html>
<!-- 需要添加
<html  xmlns:th="http://www.thymeleaf.org">
这样在后面的th标签就不会报错
 -->
<html  xmlns:th="http://www.thymeleaf.org">
<head lang="en">
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    <title th:text="${username}">xx</title>
</head>
<body>
<h1 th:text="${username}">Hello World</h1>
<h1>获取对象信息</h1>
<h2>1、通过直接访问对象的方式</h2>
<p th:text="${userInfo.username}"></p>
<p th:text="${userInfo.password}"></p>


<h2>2、通过th:object访问对象的方式</h2>
<div th:object="${userInfo}">
    <p th:text="*{username}"></p>
    <p th:text="*{password}"></p>
</div>

<h1>表单提交</h1>
<!-- 表单提交用户信息,注意字段的设置,直接是*{} -->
 <form action="#" th:action="@{/add}" th:object="${userInfo}" method="post">  
  <input type="text" th:field="*{username}" />  
  <input type="text" th:field="*{password}" />  
  <input type="submit" />  
</form> 
</body>
</html>

@ResponseBody
@RequestMapping(value="/add",method=RequestMethod.POST)
public String add(@ModelAttribute UserForm user){
    String username = user.getUsername();
    String password = user.getPassword();
    return username+"__"+password;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章