简体   繁体   中英

How to pass child class into controller in spring-mvc?

I have a parent class and its child in my application model.
And have the following controller method:

@RequestMapping(method=RequestMethod.POST, value="/page")
public String postMethod(Model model, Parent obj, BindingResult result) {
     // do something
}

but I want it to be able to handle instances of the child class, that was posted by form.
How can I do this?

You can create an object of required type as an implicit model attribute:

@ModelAttribute("parent")
public Parent createChild(@RequestParam("type") String type) {
    if ("foo".equals(type)) return new Foo();
    else if ("bar".equals(type)) return new Bar();
    else return null;
}

Since Spring doesn't remember type of the object passed to the form automatically, you need to do it yourself, by adding a hidden form field whose value specifies type of the object (a type field in the example above).

Another option is to avoid creating object from scratch by storing it in a session. It can be configured using @SessionAttributes annotaton, see 15.3.2.9 Specifying attributes to store in a session with @SessionAttributes .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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