thymeleaf实现form表单提交
话不多说,上代码
<form action="/adminStudent/toStudentDataList?currentPage=1" method="get">
<div class="col-md-3 data">
<input type="text" class="form-control input-sm" placeholder="姓名" name="studentName">
<select data-placeholder="" name="classId" class="form-control input-sm">
<option th:value="0" selected>班级</option>
<option th:each="classes:${classList}" th:value="${classes.id}" th:text="${classes.name}"></option>
</select>
</div>
<button type="submit" class="btn bg-maroon">搜索</button>
</form>
注意:
每个input标签都要有name属性,form要有action和method。
当然,这里也可以使用button代替input作为提交的按钮:
button的type属性有两个值:button和submit。当不写type属性时,其type的默认值是submit,点击的话也会直接提交数据
我们也可以用下面的方式,用一个实体类来接受所有参数:
- 创建实体
public class Greeting {
private long id;
private String content;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
- 创建Controller
@Controller
public class GreetingController {
@GetMapping("/greeting")
public String greetingForm(Model model) {
model.addAttribute("greeting", new Greeting());
return "greeting";
}
@PostMapping("/greeting")
public String greetingSubmit(@ModelAttribute Greeting greeting) {
return "result";
}
}
页面展示层
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Getting Started: Handling Form Submission</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<h1>Form</h1>
<form action="#" th:action="@{/greeting}" th:object="${greeting}" method="post">
<p>Id: <input type="text" th:field="*{id}" /></p>
<p>Message: <input type="text" th:field="*{content}" /></p>
<p><input type="submit" value="Submit" /> <input type="reset" value="Reset" /></p>
</form>
</body>
</html>
src/main/resources/templates/result.html
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Getting Started: Handling Form Submission</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<h1>Result</h1>
<p th:text="'id: ' + ${greeting.id}" />
<p th:text="'content: ' + ${greeting.content}" />
<a href="/greeting">Submit another message</a>
</body>
</html>