spacer

 

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();
}

3 comments:

Edrisse Mussá said...

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

DonQuixote said...

Yes. You can read more about it in http://static.springsource.org/spring/docs/2.5.x/reference/mvc.html#mvc-controller-multiaction

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])

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

Controller:
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;
}

JSP:

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

Am I doing something wrong? :-(

Popular Posts

Featured Post

Encrypting Properties File Values with Jasypt

Encrypting Properties File Values with Jasypt What's the fuzz all about? Property files are text resources in your standard web applic...