5

As of Spring MVC 3, AbstractCommandController is deprecated so you can no longer specify the command class in setCommandClass(). Instead you hard-code the command class in the parameter list of a request handler. For example,

@RequestMapping(method = RequestMethod.POST)
public void show(HttpServletRequest request, @ModelAttribute("employee") Employee employee)

My problem is that I'm developing a generic page that allows the user to edit a generic bean, so the command class isn't known until the run-time. If the variable beanClass holds the command class, with AbstractCommandController, you would simply do the following,

setCommandClass(beanClass)

Since I can't declare the command object as a method parameter, is there any way to have Spring bind request parameters to a generic bean in the body of the request handler?

4
  • What do you mean by a "generic bean"? Commented Oct 9, 2010 at 18:00
  • I meant a POJO. Normally, a controller uses a specific bean as its command object, but my controller needs to use any bean whose type isn't known until the runtime. The type comes from a service object. Commented Oct 9, 2010 at 18:13
  • But if the type isn't known at compile time, how are you going to use it in your code? Commented Oct 9, 2010 at 20:18
  • You can think of it as something similar to a JavaBeans property editor in some Swing-based tool. You specify a JavaBeans class you want to edit and the tool loads it to an editor. In my case, the list of beans to configure is known at compile time, but I'd like them to share the same controller since it would be redundant to have a different controller for each bean. Commented Oct 9, 2010 at 20:38

1 Answer 1

6

Instantiation of the command object is the only place where Spring needs to know a command class. However, you can override it with @ModelAttribute-annotated method:

@RequestMapping(method = RequestMethod.POST) 
public void show(HttpServletRequest request, 
    @ModelAttribute("objectToShow") Object objectToShow) 
{
    ...
}

@ModelAttribute("objectToShow")
public Object createCommandObject() {
    return getCommandClass().newInstance();
}

By the way, Spring also works fine with the real generics:

public abstract class GenericController<T> {
    @RequestMapping("/edit")  
    public ModelAndView edit(@ModelAttribute("t") T t) { ... }
}

@Controller @RequestMapping("/foo")
public class FooController extends GenericController<Foo> { ... }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.