英文标题:Handling Form Submission
在用Spring方法构建web站点,HTTP请求被一个controller处理。这些组件很容易被@Controller
标识。在下面例子中,GreetingController处理 /greeting
的Request请求。
package me.wenshan.greeting; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PostMapping; @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"; } }
这个控制类比较简单但是够用。让我们一步一步分析。这个映射注释(mapping annotations)映射HTTP request到一个控制类的方法。/greeting的request和post都被映射到controller类的两个方法上。当然你也可以用@RequestMapping
来指定所有HTTP操作(例如:GET,POST,DELETE)等。在这个例子中,采用@GetMapping
和@PostMapping
来分别指定HTTP request到greetingForm方法,指定HTTP post到greetingSubmit()上,这样不同的方法处理不同/greeting的HTT方法。greetingForm()方法使用了一个Model对象来把一个新的Greeting对象传给指定的视图模板。在接着的代码中,这个Greeting对象的id和content绑定到form对应的输入域中。
package me.wenshan.greeting; 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; } }
在这个例子中,我们使用Thymeleaf来解析greeting.html模板,并且使用变量模板来展现form。src/main/resources/templates/greeting.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>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>
这th:action="@{/greeting}"
设置指定form的POST提交到/greeting
,同时th:object="${greeting}"
申明这个Model对象用来收集表单数据。这两个表单域被用th:field="{id}"
和th:field="{content}"
来表示数据收集到这两个变量中。让我们来总结一下流程,表单(form)的提交用POST方法被/greeting处理,方法greetingSubmit()
接收到Greeting
对象,这个对象存储了表单数据。这个Greeting对象是@ModelAttribute,
这样被绑定到表单(form)内容。
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>
这个例子中使用了两个视图模板来展现表单和现实表单数据,你也可以使用一个视图模板来达到这两个目的。