• th:action 指定表单提交地址
  • th:value 给value属性赋值
  • th:field 能自动生成id、name和value属性

form表单示例

  • 运行结果
  • 更改数据
  • 点击保存

控制器代码:TestController.java
package com.example.demo.controller;

import com.example.demo.bean.Student;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@Controller
public class TestController {
   
    @RequestMapping("/edit")
    public String edit(Model model) {
   
        Student s = new Student(2019001, "小明");
        model.addAttribute("stu", s);
        return "th/form";
    }

    @RequestMapping(value = "/save", method = RequestMethod.GET)
    @ResponseBody
    public Student save(Student stu) {
   
        return stu;    //代码简洁很多
    }
}
页面代码:form.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>form</title>
    <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
    <script src="https://cdn.bootcss.com/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<form class="form-horizontal" th:action="@{/save}" method="get">
    <div class="form-group">
        <label for="id" class="col-sm-2 control-label">学号</label>
        <div class="col-sm-5">
            <input type="text" class="form-control" id="id" name="id" th:value="${stu.id}" placeholder="请输入学号">
        </div>
    </div>
    <div class="form-group">
        <label for="name" class="col-sm-2 control-label">姓名</label>
        <div class="col-sm-5">
            <input type="text" class="form-control" id="name" name="name" th:value="${stu.name}" placeholder="请输入姓名">
        </div>
    </div>
    <div class="form-group">
        <div class="col-sm-5 col-sm-offset-2">
            <button id="btn" class="btn btn-default" type="submit">保存</button>
        </div>
    </div>
</form>

</body>
</html>