Sunday, September 10, 2006

A Spring MultiActionController with Command

The following is an example Spring code on how to create a handler methond within a Spring MultiActionController that includes a Command object. The MultiActionController implementation simple checks whether a method with an additional object in the handler method signature exists. If that's the case it assumes that it is a command object and binds the request parameters to the command object.

Here Are Some Code Examples

A typical Spring MultiActionController does not contain a command object in the method signature.

public ModelAndView myHandler(HttpServletRequest request, 
        HttpServletResponse response) {
    // handler methods here

A Spring MultiActionController with a Command object passed as an additional parameter in the method signature.

public ModelAndView myHandler(HttpServletRequest request, 
        HttpServletResponse response, Object command) {
    MyObjectCommand command = (MyObjectCommand) command; 

The creation of the command object can be overloaded as well.

protected Object newCommandObject(Class clazz) 
        throws Exception {
    return new MyObjectCommand();


edrisse said...

Hi. Is it possible to have commands of diferent classes depending on the method being invoked?

Antonio Lagnada said...

Yes. You can read more about it in

The object you passed will automatically be bound/populated with the parameters retrieved from the request.

The method signature may look like this:

// 'anyMeaningfulName' can be replaced by any method name
public [ModelAndView | Map | void] anyMeaningfulName(HttpServletRequest, HttpServletResponse [,HttpSession] [,AnyObject])

Jiřík said...

Hi, I just tried to use you code but I have a problem with Command object mapping. Still getting (neither bindingresult nor plain target object for bean name available as request attribute).

public ModelAndView detail(HttpServletRequest request, HttpServletResponse response, Object command) {
ArticleCommentCommand formCommand = (ArticleCommentCommand) command;
String articleCommentCommandName = getCommandName(formCommand);
ModelAndView mav = new ModelAndView("articles/detail");
mav.addObject("articleCommentCommand", articleCommentCommandName);
return mav;


form:form action="${formUrl}" method="post" commandName="${articleCommentCommand}" cssClass="standardInputForm" name="addArticleComment">

Am I doing something wrong? :-(