Karthik's Weblog

Learn to customize Spring MVC @Controller method arguments

Posted in Spring by karthik on November 8, 2009

Spring MVC Annotation based controllers offers a lot of flexibility w.r.t Annotated controller handler method signature.
Refer to the Spring MVC documentation to get a detailed list of supported argument types & annotations.

What is interesting is that in addition to the supported controller method argument types , you can add support for custom argument types as well. You just need to provide a WebArgumentResolver interface implementation that knows how to resolve a particular controller method argument.

The interface definition is reproduced here for convenience -

    public interface WebArgumentResolver{ 
Object resolveArgument(MethodParameter methodParameter, NativeWebRequest webRequest);

Next let’s build a case for rolling out your own WebArgumentResolver implementation.

If you are trying to extract the value for the servlet request param ‘id’, instead of accessing the “raw” servlet apis as shown below -

class MyController{
public void test(HttpServletRequest request){
String id = request.getParameter("id");

you could use a built-in annotation like this -

class MyController{
public void test(@RequestParam(value="id") String id){


While both the code snippets achieve the same thing, the latter is probably more unit-test friendly and doesn’t require you to mock HttpServletRequest object as is the case with the former. In other words, the annotations preserve the POJO-ness of your @Controller. (In reality, the preceding code snippets don’t actually mean the same thing – Spring takes care of invoking the databinder, registered property editors as well when it sees a @RequestParam annotation.

Now let’s say you want to access a http session variable ‘user’, this is the way you would do it in a Controller –

class MyController{
// Spring injects the current HttpSession variable at runtime into the 'test' method.
public void test(HttpSession session){
String user = (String)session.getAttribute("user");

While this works, it doesn’t seem consistent with the annotation based approach.

An annotation similar to @RequestParam albeit for accessing Http Session parameters could look like this –

  package com.springmvc.extensions; 

public @interface SessionParam {
/** * The name of the Session attribute to bind to. */ String value() default "";
/** * Whether the parameter is required. * Default is true, leading to an exception thrown in case * of the parameter missing in the request. Switch this to * false if you prefer a * null in case of the parameter missing. * Alternatively, provide a {@link #defaultValue() defaultValue}, * which implicitely sets this flag to false. */ boolean required() default true;
/** * The default value to use as a fallback. Supplying a default value * implicitely sets {@link #required()} to false. */ String defaultValue() default "";

Next, let's define the argument resolver -

  package com.springmvc.extensions;

  import java.lang.annotation.Annotation;

  import javax.servlet.http.HttpServletRequest;
  import javax.servlet.http.HttpSession;

  import org.springframework.core.MethodParameter;
  import org.springframework.web.HttpSessionRequiredException;
  import org.springframework.web.bind.support.WebArgumentResolver;
  import org.springframework.web.context.request.NativeWebRequest;

  public class SessionParamArgumentResolver implements WebArgumentResolver {

    public Object resolveArgument(MethodParameter param,
        NativeWebRequest request) throws Exception {

      Annotation[] paramAnns = param.getParameterAnnotations();   #1
      Class paramType = param.getParameterType();

      for (Annotation paramAnn : paramAnns) {                     
        if (SessionParam.class.isInstance(paramAnn)) {            #2
          SessionParam sessionParam = (SessionParam) paramAnn;
          String paramName = sessionParam.value();
          boolean required = sessionParam.required();
          String defaultValue = sessionParam.defaultValue();
          HttpServletRequest httprequest = (HttpServletRequest) request
          HttpSession session = httprequest.getSession(false);
          Object result = null;
          if (session != null) {
            result = session.getAttribute(paramName);
          if (result == null)
            result = defaultValue;
          if (result == null && required && session == null)
            raiseSessionRequiredException(paramName, paramType);  #3
          if (result == null && required)
            raiseMissingParameterException(paramName, paramType); #4

          return result;

      return WebArgumentResolver.UNRESOLVED;                      #5


    // ..

    protected void raiseMissingParameterException(String paramName,
        Class paramType) throws Exception {
      throw new IllegalStateException("Missing parameter '" + paramName
          + "' of type [" + paramType.getName() + "]");

    protected void raiseSessionRequiredException(String paramName,
        Class paramType) throws Exception {
      throw new HttpSessionRequiredException(
          "No HttpSession found for resolving parameter '" + paramName
              + "' of type [" + paramType.getName() + "]");


Explanation -
#1 looks up the annotations specified on the method argument
#2 checks if the method argument annotation is of type @SessionParam
#3 throws an exception if the param is marked as 'required' and no valid session exists
#4 throws an exception if the param is not found in the http session
#5 You could configure a list of WebArgumentResolver-s. In this example, we have only one.
If the argument resolver fails to resolve the argument successfully, its imperative that you return the special object WebArgumentResolver.UNRESOLVED. That way Spring knows that it needs to consult with other argument resolver-s to resolve the a given controller method parameter. A return value of "null" from a WebArgumentResolver is considered valid and the method parameter is marked as 'resolved'!

Next we will discuss how to configure the SessionParamArgumentResolver class

AnnotationMethodHandlerAdapter class that ships with Spring is a HandlerAdapter implementation that is specifically designated to handle request intended for controllers based on the Annotation model. One of the primary responsibilities of this handler adapter is to 'resolve' all the handler method arguments prior to invoking the handler method.

While the AnnotationMethodHandlerAdapter knows how to resolve all the standard argument types, it consults the configured WebArgumentResolver-s for resolving the arguments that are not supported by default.

So next let's configure the custom WebArgumentResolver that we just developed -

<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">     
   <property name="customArgumentResolver" ref="sessionArgResolver"/>
<bean id="sessionArgResolver" class=quot;com.springmvc.SessionParamArgumentResolver"/>

With the preceeding Spring bean configuration in place, you could rewrite your controller like this -

class MyController{
public void test(@SessionParam(value="user") String user){

Hopefully this article gives you a good idea of how to customize Spring MVC @Controller to suit your needs.


Get every new post delivered to your Inbox.