简体   繁体   English

@ModelAttribute在方法签名中使用@ModelAttribute注释方法

[英]@ModelAttribute annotated method WITH @ModelAttribute in method signature

I was wondering if it is possible to chain @ModelAttribute methods by having an @ModelAttribute annotated, but not request mapped, method use another ModelAttribute in the method signature. 我想知道是否可以通过注释@ModelAttribute链接@ModelAttribute方法,但不是请求映射,方法在方法签名中使用另一个ModelAttribute。 This would be in a controller. 这将在控制器中。

ie

@ModelAttribute("attrOne")
public AttrOne getAttrOne() {
    return service.getAttOne();
}

@ModelAttribute("attrTwo")
public AttrTwo getAttrTwo(@ModelAttribute("attrOne") AttrOne attrOne){
    return anotherservice.getAttrTwo(attrOne);      
}

Then if there was a request mapped method that did this: 然后,如果有一个请求映射方法执行此操作:

@RequestMapping(method=RequestMethod.GET)
public String doSomething(@ModelAttribute("attrTwo") AttrTwo attrTwo )

would this work? 这会有用吗?

I seem to get a null object for AttrOne in the second annotated method... as the first annotated method is not called by the second one... 我似乎在第二个带注释的方法中为AttrOne获取了一个空对象...因为第一个带注释的方法没有被第二个注释...

Cheers 干杯

I ran into the same situation by learning from the spring documention: 通过学习春季文档,我遇到了同样的情况:

@ModelAttribute is also used at the method level [..] . @ModelAttribute也用于方法级别[..] For this usage the method signature can contain the same types as documented above for the @RequestMapping annotation. 对于此用法,方法签名可以包含与上面针对@RequestMapping批注记录的相同类型。

I found SPR-6299 which faces this problem. 我发现SPR-6299面临这个问题。 In the comments you can find a workaround by providing only one @ModelAttribute annotated method which sets the attributes into the model: 在注释中,您可以通过提供一个 @ModelAttribute注释方法来找到解决方法,该方法将属性设置到模型中:

@ModelAttribute
public void populateModel(Model model) { 
  model.addAttribute("attrOne", getAttrOne());
  model.addAttribute("attrTwo", getAttrTwo());
}

根据SPR-6299 ,这将在Spring 4.1 RC1或更高版本中实现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM