gpt4 book ai didi

java - spring中@ModelAttribute、model.addAttribute有什么区别?

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:48:32 32 4
gpt4 key购买 nike

我是新的 Spring 学习者。我真的很困惑这两个概念之间的区别:

  1. @模型属性
  2. model.addAttribute

下面有两个“user”值。它们是一样的东西吗?我为什么要这样使用?谢谢大家

@RequestMapping(method = RequestMethod.GET)
public String setupForm(ModelMap model) {
model.addAttribute("user", new User());
return "editUser";
}

@RequestMapping(method = RequestMethod.POST)
public String processSubmit( @ModelAttribute("user") User user, BindingResult result, SessionStatus status) {
userStorageDao.save(user);
status.setComplete();
return "redirect:users.htm";
}

最佳答案

当用于参数时,@ModelAttribute 的行为如下:

An @ModelAttribute on a method argument indicates the argument should be retrieved from the model. If not present in the model, the argument should be instantiated first and then added to the model. Once present in the model, the argument’s fields should be populated from all request parameters that have matching names. This is known as data binding in Spring MVC, a very useful mechanism that saves you from having to parse each form field individually. http://docs.spring.io/spring/docs/4.1.0.BUILD-SNAPSHOT/spring-framework-reference/htmlsingle/#mvc-ann-modelattrib-method-args

这是一个非常强大的功能。在您的示例中,用户对象由 Spring 自动从 POST 请求填充。

然而,第一种方法只是创建一个 User 实例并将其添加到模型中。可以这样写以受益于@ModelAttribute:

@RequestMapping(method = RequestMethod.GET)
public String setupForm(@ModelAttribute User user) {
// user.set...
return "editUser";
}

关于java - spring中@ModelAttribute、model.addAttribute有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23576213/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com