Spring MVC @ModelAttribute方法

Kam*_*ore 15 spring-mvc modelattribute

有关Spring MVC @ModelAttribute方法的问题,在控制器@RequestMapping方法中设置模型属性与使用@ModelAttribute方法单独设置属性,哪一个被认为更好并且更常用?

从设计的角度来看,哪种方法从以下方面考虑更好:

方法1

@ModelAttribute("message")
public String addMessage(@PathVariable("userName") String userName, ModelMap model) {

  LOGGER.info("addMessage - " + userName);
  return "Spring 3 MVC Hello World - "  + userName;
}

@RequestMapping(value="/welcome/{userName}", method = RequestMethod.GET)
public String printWelcome(@PathVariable("userName") String userName, ModelMap model) {

  LOGGER.info("printWelcome - " + userName);
  return "hello";
}   
Run Code Online (Sandbox Code Playgroud)

方法2

@RequestMapping(value="/welcome/{userName}", method = RequestMethod.GET)
public String printWelcome(@PathVariable("userName") String userName, ModelMap model) {

  LOGGER.info("printWelcome - " + userName);

  model.addAttribute("message", "Spring 3 MVC Hello World - "  + userName);

  return "hello";
}   
Run Code Online (Sandbox Code Playgroud)

Ank*_*hal 19

@ModelAttribute annotation取决于如何使用它有两个目的:

在方法级别

使用@ModelAttribute在方法级别为模型提供参考数据.@ModelAttribute注释方法在选定的带@RequestMapping注释的处理程序方法之前执行.它们有效地使用通常从数据库加载的特定属性预填充隐式模型.然后,可以通过@ModelAttribute所选处理程序方法中的带注释处理程序方法参数访问此类属性,可能已对其应用绑定和验证.

换一种说法; 注释的方法@ModelAttribute将填充模型中指定的"键".这发生在@RequestMapping At Method Parameter级别之前

在方法参数级别

放置@ModelAttribute方法参数时,@ModelAttribute将模型属性映射到特定的带注释的方法参数.这是控制器获取对包含表单中输入数据的对象的引用.

例子

方法级别

@Controller
public class MyController {
    @ModelAttribute("productsList")
    public Collection<Product> populateProducts() {
        return this.productsService.getProducts();
    }
   }
Run Code Online (Sandbox Code Playgroud)

因此,在上面的示例中,productsList模型中的" "在@RequestMapping执行之前填充.

方法参数级别

@Controller
public class MyController {
    @RequestMapping(method = RequestMethod.POST)
    public String processSubmit(@ModelAttribute("product") Product myProduct, BindingResult result, SessionStatus status) {

        new ProductValidator().validate(myProduct, result);
        if (result.hasErrors()) {
            return "productForm";
        }
        else {
            this.productsService.saveProduct(myProduct);
            status.setComplete();
            return "productSaved";
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

看看这里与实例的详细信息.


Bar*_*art 14

一个并不比另一个好.它们都有另一个目的.

  • 方法:如果您需要始终使用某些属性填充特定控制器的模型,则方法级别@ModelAttribute更有意义.
  • 参数:如果要从请求绑定数据并将其隐式添加到模型,请在参数上使用它.

回答关于更好方法的问题

我会说方法2更好,因为数据特定于该处理程序.