【发布时间】:2020-02-08 08:04:15
【问题描述】:
您好,我对@ModelAttribute 注释有疑问。据我了解,我们在方法参数中使用 @ModelAttribute 从模型中获取数据。但是很难清楚地理解它何时以及如何使用。 (代码示例来自 Spring in Action 5 书) 为什么在这种情况下,在 public String processOrder() 方法的下面代码中,我们不在 @Valid Order order
上使用 @ModelAttribute 注释 @Controller
@RequestMapping("/orders")
@SessionAttributes("order")
public class OrderController {
private OrderRepository orderRepo;
public OrderController(OrderRepository orderRepo) {
this.orderRepo = orderRepo;
}
@GetMapping("/current")
public String orderForm(@AuthenticationPrincipal User user,
@ModelAttribute Order order) {
if (order.getDeliveryName() == null) {
order.setDeliveryName(user.getFullname());
}
//following conditions
return "orderForm";
}
@PostMapping
public String processOrder(@Valid Order order, Errors errors, // <<< Here
SessionStatus sessionStatus,
@AuthenticationPrincipal User user) {
if (errors.hasErrors()) {
return "orderForm";
}
order.setUser(user);
orderRepo.save(order);
sessionStatus.setComplete();
return "redirect:/";
}
}
但在这种情况下,DesignTacoController 类,方法 processDesign() 上的@ModelAttribute 用于@Valid Taco taco:
@Slf4j
@Controller
@RequestMapping("/design")
public class DesignTacoController {
@PostMapping
public String processDesign(@Valid @ModelAttribute("design") Taco design, // <<< Here
Errors errors, Model model) {
if (errors.hasErrors()) {
return "design";
}
// Save the taco design...
// We'll do this in chapter 3
log.info("Processing design: " + design);
return "redirect:/orders/current";
}
然后在下一章作者从同一 DesignTacoController 类的 processDesign() 方法中删除 @ModelAttribute。
@Controller
@RequestMapping("/design")
@SessionAttributes("order")
@Slf4j
public class DesignTacoController {
@ModelAttribute(name = "order")
public Order order() {
return new Order();
}
@ModelAttribute(name = "design")
public Taco design() {
return new Taco();
}
@PostMapping
public String processDesign(
@Valid Taco taco, Errors errors, // <<< Here
@ModelAttribute Order order) {
log.info(" --- Saving taco");
if (errors.hasErrors()) {
return "design";
}
Taco saved = tacoRepo.save(taco);
order.addDesign(saved);
return "redirect:/orders/current";
}
在这段代码中 sn-p(来自上面的代码):
@PostMapping
public String processDesign(
@Valid Taco taco, Errors errors, // <<< Here
@ModelAttribute Order order) {
....
}
书上的引用:“Order 参数用@ModelAttribute 注释以表明它的 值应该来自模型并且 Spring MVC 不应该尝试绑定 向它请求参数。” 这个我不明白作者在这里的意思,因为在所有教程中都说当@ModelAttribute用作方法参数时,它会将请求参数绑定到它。使用 POJO bean 绑定表单数据,模型属性填充来自提交的表单的数据。
【问题讨论】:
-
对于您对书中报价的查询,您可以在这里找到答案。 stackoverflow.com/a/42198051/2825798
-
1.我不明白我们什么时候使用 Valid ModelAttribute Object 对象,什么时候 Valid Object 对象就足够了。 2/3。在您的链接中,据说“ModelAttribute 用于绑定来自请求参数的数据”,我从书中引用说我们使用 ModelAttribute“Spring 不应该尝试绑定请求参数”。我不明白,因为对我来说这两个引用相互矛盾
标签: java spring spring-boot spring-mvc modelattribute