org.springframework.web.servlet.mvc
Class BaseCommandController

java.lang.Object
  extended by org.springframework.context.support.ApplicationObjectSupport
      extended by org.springframework.web.context.support.WebApplicationObjectSupport
          extended by org.springframework.web.servlet.support.WebContentGenerator
              extended by org.springframework.web.servlet.mvc.AbstractController
                  extended by org.springframework.web.servlet.mvc.BaseCommandController
All Implemented Interfaces:
ApplicationContextAware, Controller
Direct Known Subclasses:
AbstractCommandController, AbstractFormController

public abstract class BaseCommandController
extends AbstractController

Controller implementation which creates an object (the command object) on receipt of a request and attempts to populate this object with request parameters.

This controller is the base for all controllers wishing to populate JavaBeans based on request parameters, validate the content of such JavaBeans using Validators and use custom editors (in the form of PropertyEditors) to transform objects into strings and vice versa, for example. Three notions are mentioned here:

Command class:
An instance of the command class will be created for each request and populated with request parameters. A command class can basically be any Java class; the only requirement is a no-arg constructor. The command class should preferably be a JavaBean in order to be able to populate bean properties with request parameters.

Populating using request parameters and PropertyEditors:
Upon receiving a request, any BaseCommandController will attempt to fill the command object using the request parameters. This is done using the typical and well-known JavaBeans property notation. When a request parameter named 'firstName' exists, the framework will attempt to call setFirstName([value]) passing the value of the parameter. Nested properties are of course supported. For instance a parameter named 'address.city' will result in a getAddress().setCity([value]) call on the command class.

It's important to realise that you are not limited to String arguments in your JavaBeans. Using the PropertyEditor-notion as supplied by the java.beans package, you will be able to transform Strings to Objects and the other way around. For instance setLocale(Locale loc) is perfectly possible for a request parameter named locale having a value of en, as long as you register the appropriate PropertyEditor in the Controller (see initBinder() for more information on that matter.

Validators: After the controller has successfully populated the command object with parameters from the request, it will use any configured validators to validate the object. Validation results will be put in a Errors object which can be used in a View to render any input problems.

Workflow (and that defined by superclass):
Since this class is an abstract base class for more specific implementation, it does not override the handleRequestInternal() method and also has no actual workflow. Implementing classes like AbstractFormController, AbstractcommandController, SimpleFormController and AbstractWizardFormController provide actual functionality and workflow. More information on workflow performed by superclasses can be found here.

Exposed configuration properties (and those defined by superclass):

name default description
commandName command the name to use when binding the instantiated command class to the request
commandClass null the class to use upon receiving a request and which to fill using the request parameters. What object is used and whether or not it should be created is defined by extending classes and their configuration properties and methods.
validator null Validator bean (usually passed in using a <ref bean="beanId"/> property. The validator will be called at appropriate places in the workflow of subclasses (have a look at those for more info) to validate the command object.
validateOnBinding true Indicates whether or not to validate the command object after the object has been populated with request parameters.

Author:
Rod Johnson, Juergen Hoeller

Field Summary
static String DEFAULT_COMMAND_NAME
           
 
Fields inherited from class org.springframework.web.servlet.support.WebContentGenerator
HEADER_CACHE_CONTROL, HEADER_EXPIRES, HEADER_PRAGMA, METHOD_GET, METHOD_HEAD, METHOD_POST
 
Fields inherited from class org.springframework.context.support.ApplicationObjectSupport
logger
 
Constructor Summary
BaseCommandController()
           
 
Method Summary
protected  ServletRequestDataBinder bindAndValidate(HttpServletRequest request, Object command)
          Bind the parameters of the given request to the given command object.
protected  boolean checkCommand(Object command)
          Check if the given command object is a valid for this controller, i.e. its command class.
protected  ServletRequestDataBinder createBinder(HttpServletRequest request, Object command)
          Create a new binder instance for the given command and request.
protected  Object createCommand()
          Create a new command instance for the command class of this controller.
protected  Object getCommand(HttpServletRequest request)
          Retrieve a command object for the given request.
 Class getCommandClass()
          Return the command class for this controller.
 String getCommandName()
          Return the name of the command in the model.
 MessageCodesResolver getMessageCodesResolver()
          Return the strategy to use for resolving errors into message codes.
 Validator getValidator()
           
 Validator[] getValidators()
           
protected  void initApplicationContext()
          Subclasses can override this for custom initialization behavior.
protected  void initBinder(HttpServletRequest request, ServletRequestDataBinder binder)
          Initialize the given binder instance, for example with custom editors.
 boolean isValidateOnBinding()
          Return if the Validator should get applied when binding.
protected  void onBind(HttpServletRequest request, Object command)
          Callback for custom post-processing in terms of binding.
protected  void onBind(HttpServletRequest request, Object command, BindException errors)
          Callback for custom post-processing in terms of binding.
protected  void onBindAndValidate(HttpServletRequest request, Object command, BindException errors)
          Callback for custom post-processing in terms of binding and validation.
 void setCommandClass(Class commandClass)
          Set the command class for this controller.
 void setCommandName(String commandName)
          Set the name of the command in the model.
 void setMessageCodesResolver(MessageCodesResolver messageCodesResolver)
          Set the strategy to use for resolving errors into message codes.
 void setValidateOnBinding(boolean validateOnBinding)
          Set if the Validator should get applied when binding.
 void setValidator(Validator validator)
          Set the primary Validator for this controller.
 void setValidators(Validator[] validators)
          Set the Validators for this controller.
protected  boolean suppressValidation(HttpServletRequest request)
          Return whether to suppress validation for the given request.
 
Methods inherited from class org.springframework.web.servlet.mvc.AbstractController
handleRequest, handleRequestInternal, isSynchronizeOnSession, setSynchronizeOnSession
 
Methods inherited from class org.springframework.web.servlet.support.WebContentGenerator
applyCacheSeconds, applyCacheSeconds, cacheForSeconds, cacheForSeconds, checkAndPrepare, checkAndPrepare, getCacheSeconds, getSupportedMethods, isRequireSession, isUseCacheControlHeader, isUseExpiresHeader, preventCaching, setCacheSeconds, setRequireSession, setSupportedMethods, setUseCacheControlHeader, setUseExpiresHeader
 
Methods inherited from class org.springframework.web.context.support.WebApplicationObjectSupport
getServletContext, getTempDir, getWebApplicationContext, isContextRequired
 
Methods inherited from class org.springframework.context.support.ApplicationObjectSupport
getApplicationContext, getMessageSourceAccessor, requiredContextClass, setApplicationContext
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

DEFAULT_COMMAND_NAME

public static final String DEFAULT_COMMAND_NAME
See Also:
Constant Field Values
Constructor Detail

BaseCommandController

public BaseCommandController()
Method Detail

setCommandName

public final void setCommandName(String commandName)
Set the name of the command in the model. The command object will be included in the model under this name.


getCommandName

public final String getCommandName()
Return the name of the command in the model.


setCommandClass

public final void setCommandClass(Class commandClass)
Set the command class for this controller. An instance of this class gets populated and validated on each request.


getCommandClass

public final Class getCommandClass()
Return the command class for this controller.


setValidators

public final void setValidators(Validator[] validators)
Set the Validators for this controller. The Validator must support the specified command class.


getValidators

public final Validator[] getValidators()
Returns:
the primary Validator for this controller.

setValidator

public final void setValidator(Validator validator)
Set the primary Validator for this controller. The Validator must support the specified command class. If there are one or more existing validators set already when this method is called, only the specified validator will be kept. Use setValidators(Validator[]) to set multiple validators.


getValidator

public final Validator getValidator()
Returns:
the Validators for this controller.

setValidateOnBinding

public final void setValidateOnBinding(boolean validateOnBinding)
Set if the Validator should get applied when binding.


isValidateOnBinding

public final boolean isValidateOnBinding()
Return if the Validator should get applied when binding.


setMessageCodesResolver

public final void setMessageCodesResolver(MessageCodesResolver messageCodesResolver)
Set the strategy to use for resolving errors into message codes. Applies the given strategy to all data binders used by this controller.

Default is null, i.e. using the default strategy of the data binder.

See Also:
createBinder(javax.servlet.http.HttpServletRequest, java.lang.Object), DataBinder.setMessageCodesResolver(org.springframework.validation.MessageCodesResolver)

getMessageCodesResolver

public final MessageCodesResolver getMessageCodesResolver()
Return the strategy to use for resolving errors into message codes.


initApplicationContext

protected void initApplicationContext()
Description copied from class: ApplicationObjectSupport
Subclasses can override this for custom initialization behavior. Gets called by setApplicationContext after setting the context instance.

Note: Does not get called on reinitialization of the context but rather just on first initialization of this object's context reference.

Overrides:
initApplicationContext in class ApplicationObjectSupport
See Also:
ApplicationObjectSupport.setApplicationContext(org.springframework.context.ApplicationContext)

getCommand

protected Object getCommand(HttpServletRequest request)
                     throws Exception
Retrieve a command object for the given request.

Default implementation calls createCommand. Subclasses can override this.

Parameters:
request - current HTTP request
Returns:
object command to bind onto
Throws:
Exception
See Also:
createCommand()

createCommand

protected final Object createCommand()
                              throws InstantiationException,
                                     IllegalAccessException
Create a new command instance for the command class of this controller.

Returns:
the new command instance
Throws:
InstantiationException - if the command class could not be instantiated
IllegalAccessException - if the class or its constructor is not accessible

checkCommand

protected final boolean checkCommand(Object command)
Check if the given command object is a valid for this controller, i.e. its command class.

Parameters:
command - the command object to check
Returns:
if the command object is valid for this controller

bindAndValidate

protected final ServletRequestDataBinder bindAndValidate(HttpServletRequest request,
                                                         Object command)
                                                  throws Exception
Bind the parameters of the given request to the given command object.

Parameters:
request - current HTTP request
command - the command to bind onto
Returns:
the ServletRequestDataBinder instance for additional custom validation
Throws:
Exception - in case of invalid state or arguments

createBinder

protected ServletRequestDataBinder createBinder(HttpServletRequest request,
                                                Object command)
                                         throws Exception
Create a new binder instance for the given command and request.

Called by bindAndValidate. Can be overridden to plug in custom ServletRequestDataBinder subclasses.

Default implementation creates a standard ServletRequestDataBinder, sets the specified MessageCodesResolver (if any), and invokes initBinder. Note that initBinder will not be invoked if you override this method!

Parameters:
request - current HTTP request
command - the command to bind onto
Returns:
the new binder instance
Throws:
Exception - in case of invalid state or arguments
See Also:
bindAndValidate(javax.servlet.http.HttpServletRequest, java.lang.Object), initBinder(javax.servlet.http.HttpServletRequest, org.springframework.web.bind.ServletRequestDataBinder), setMessageCodesResolver(org.springframework.validation.MessageCodesResolver)

initBinder

protected void initBinder(HttpServletRequest request,
                          ServletRequestDataBinder binder)
                   throws Exception
Initialize the given binder instance, for example with custom editors. Called by createBinder.

This method allows you to register custom editors for certain fields of your command class. For instance, you will be able to transform Date objects into a String pattern and back, in order to allow your JavaBeans to have Date properties and still be able to set and display them in an HTML interface.

Default implementation is empty.

Parameters:
request - current HTTP request
binder - new binder instance
Throws:
Exception - in case of invalid state or arguments
See Also:
createBinder(javax.servlet.http.HttpServletRequest, java.lang.Object), DataBinder.registerCustomEditor(java.lang.Class, java.beans.PropertyEditor), CustomDateEditor

onBind

protected void onBind(HttpServletRequest request,
                      Object command,
                      BindException errors)
               throws Exception
Callback for custom post-processing in terms of binding. Called on each submit, after standard binding but before validation.

Default implementation delegates to onBind(request, command).

Parameters:
request - current HTTP request
command - the command object to perform further binding on
errors - validation errors holder, allowing for additional custom registration of binding errors
Throws:
Exception - in case of invalid state or arguments
See Also:
bindAndValidate(javax.servlet.http.HttpServletRequest, java.lang.Object), onBind(HttpServletRequest, Object)

onBind

protected void onBind(HttpServletRequest request,
                      Object command)
               throws Exception
Callback for custom post-processing in terms of binding. Called by the default implementation of the onBind version with all parameters, after standard binding but before validation.

Default implementation is empty.

Parameters:
request - current HTTP request
command - the command object to perform further binding on
Throws:
Exception - in case of invalid state or arguments
See Also:
onBind(HttpServletRequest, Object, BindException)

suppressValidation

protected boolean suppressValidation(HttpServletRequest request)
Return whether to suppress validation for the given request.

Default implementation always returns false. Can be overridden in subclasses to suppress validation, for example, if a special request parameter is set.

Parameters:
request - current HTTP request
Returns:
whether to suppress validation for the given request

onBindAndValidate

protected void onBindAndValidate(HttpServletRequest request,
                                 Object command,
                                 BindException errors)
                          throws Exception
Callback for custom post-processing in terms of binding and validation. Called on each submit, after standard binding and validation, but before error evaluation.

Default implementation is empty.

Parameters:
request - current HTTP request
command - the command object, still allowing for further binding
errors - validation errors holder, allowing for additional custom validation
Throws:
Exception - in case of invalid state or arguments
See Also:
bindAndValidate(javax.servlet.http.HttpServletRequest, java.lang.Object), Errors


Copyright (c) 2002-2005 The Spring Framework Project.