0

I have an action method on a Spring MVC controller that has an argument annotated with @ModelAttribute. However, I don't know at compile time what the type of this parameter will be - I know the abstract base type but not the derived type.

At runtime, I will be able to decide what class I am expecting and I will be able to get a new'd up instance of this class. However, I have no idea what code I should be calling to parse the request data in the same fashion that @ModelAttribute does.

I've looked around and it seems that if i can get a hold of a WebRequestDataBinder I can use that to populate my object, but for that I need a BinderFactory and this is where I kind of get lost.

Can anyone give me some pointers here - or tell me that I am looking at it the wrong way and need to do something else?

efdee
  • 2,255
  • 3
  • 20
  • 26

1 Answers1

0

you can inject the model itself in your controllers method and access the attribute yourself.

@RequestMapping(...)
public void doStuff(ModelMap model) {
    Object attr = model.get("nameOfAttribute");
    // ...
}
Yevgeniy
  • 2,614
  • 1
  • 19
  • 26
  • Will this also work for complex objects, or just primitive values? How will it know what class to use? – efdee Dec 06 '12 at 13:02
  • @efdee it will work for whatever type you put in the model... when i consider your comment, it sounds like you are talking about `@RequestParam` and not about `@ModelAttribute`. Working with `@ModelAttribute` you normally control what is inside the model. maybe we talk at cross-purposes. could you provide some code to clearify what your are doing? – Yevgeniy Dec 06 '12 at 13:16
  • I thought `@RequestParam` is for parameters coming from the request mapping, eg. for '/users/:id', id would be a `@RequestParam`. I have a form that contains data and I want to post it back to my controller. I've used `@ModelAttribute` in the past to get the data into an actual object. However, this particular form is built dynamically, so I can't at compile time specify the concrete class to use for parsing the data. I can, however, at runtime inspect some things so I end up knowing what type it will be. – efdee Dec 06 '12 at 13:24
  • Seems like my assumption about `@RequestParam` is wrong. I'll have to go back to the books and learn what the difference is exactly. Same question though, how do I invoke this manually inside the method, instead of using an annotation on the method parameter? – efdee Dec 06 '12 at 13:26