4

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. 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...

Cheers

2
  • for getAttrTwo() why would you need to pass attrOne? couldn't you just make the same service call or possibly cache the result of the service call? Commented Mar 28, 2011 at 20:47
  • more explanation: I would like to have both these in a one super class controller but override the first method in extending controllers.... Commented Mar 29, 2011 at 18:59

2 Answers 2

4

I ran into the same situation by learning from the spring documention:

@ModelAttribute is also used at the method level [..]. For this usage the method signature can contain the same types as documented above for the @RequestMapping annotation.

I found SPR-6299 which faces this problem. In the comments you can find a workaround by providing only one @ModelAttribute annotated method which sets the attributes into the model:

@ModelAttribute public void populateModel(Model model) { model.addAttribute("attrOne", getAttrOne()); model.addAttribute("attrTwo", getAttrTwo()); } 
Sign up to request clarification or add additional context in comments.

Comments

1

According to SPR-6299, this will be possible in Spring 4.1 RC1 or later.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.