2.2 处理表单提交
2.2 处理表单提交
如果在视图中查看 <form>
标签,可以看到它的 method
属性被设置为<form>
没有声明 action
属性。这意味着在提交表单时,浏览器将收集表单中的所有数据,并通过/design
路径。
因此,需要在该DesignTacoController
中编写一个新的处理程序方法来处理 /design
接口的
在程序清单@GetMapping
注释指定 showDesignForm()
方法应该处理/design
。与 @GetMapping
处理@PostMapping
处理processDesign()
方法添加到 DesignTacoController
中。程序清单
@PostMapping
public String processDesign(Design design) {
// Save the taco design...
// We'll do this in chapter 3
log.info("Processing design: " + design);
return "redirect:/orders/current";
}
当应用到 processDesign()
方法时,@PostMapping
与类级别 @RequestMapping
相协调,以表明 processDesign()
应该处理 /design
接口的
提交表单时,表单中的字段被绑定到 Taco
对象的属性(其类在下一个程序清单中显示processDesign()
。从这里开始,processDesign()
方法可以对 Taco
对象做任何它想做的事情。程序清单
package tacos;
import java.util.List;
import lombok.Data;
@Data
public class Taco {
private String name;
private List<String> ingredients;
}
如果查看程序清单
表单上的List<String>
,它将捕获每个选择的配料。
目前,
与
这样做的想法源于,在创建了一个玉米饼之后,用户将被重定向到一个订单表单,他们可以从该表单下订单,以交付他们的玉米饼。但是还没有一个控制器来处理
根据现在对
package tacos.web;
import javax.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import lombok.extern.slf4j.Slf4j;
import tacos.Order;
@Slf4j
@Controller
@RequestMapping("/orders")
public class OrderController {
@GetMapping("/current")
public String orderForm(Model model) {
model.addAttribute("order", new Order());
return "orderForm";
}
}
同样,可以使用
类级别的
至于
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
<title>Taco Cloud</title>
<link rel="stylesheet" th:href="@{/styles.css}" />
</head>
<body>
<form method="POST" th:action="@{/orders}" th:object="${order}">
<h1>Order your taco creations!</h1>
<img th:src="@{/images/TacoCloud.png}" />
<a th:href="@{/design}" id="another">Design another taco</a><br />
<div th:if="${#fields.hasErrors()}">
<span class="validationError">
Please correct the problems below and resubmit.
</span>
</div>
<h3>Deliver my taco masterpieces to...</h3>
<label for="name">Name: </label>
<input type="text" th:field="*{name}" />
<br />
<label for="street">Street address: </label>
<input type="text" th:field="*{street}" />
<br />
<label for="city">City: </label>
<input type="text" th:field="*{city}" />
<br />
<label for="state">State: </label>
<input type="text" th:field="*{state}" />
<br />
<label for="zip">Zip code: </label>
<input type="text" th:field="*{zip}" />
<br />
<h3>Here's how I'll pay...</h3>
<label for="ccNumber">Credit Card #: </label>
<input type="text" th:field="*{ccNumber}" />
<br />
<label for="ccExpiration">Expiration: </label>
<input type="text" th:field="*{ccExpiration}" />
<br />
<label for="ccCVV">CVV: </label>
<input type="text" th:field="*{ccCVV}" />
<br />
<input type="submit" value="Submit order" />
</form>
</body>
</html>
在大多数情况下,