Spring Annotation Based Controllers

Spring 2.5 introduced support for annotation based MVC controllers. @RequestMapping, @RequestParam, @ModelAttribute are some of the annotations provided for this implementation. We have seen about these controller annotations at high level in a previous tutorial on spring MVC. I will be using the same code available in that tutorial to explain the annotations.

An important note, SimpleFormController is deprecated so do not use it. Spring may remove it from the next major version from the API. Go with annotation based controllers and it is easy to use. Using annotation based controllers means we need not extend some defined base class and need not implement some specific interfaces.

To brush up the basics of annotations I recommend you to go through my tutorial on java annotations.

@Controller Annotation

In spring-context first we need to declare a bean. This is just a stand spring bean definition in dispatcher’s context.

Latest way of doing this is, enabling autodetection. For the @Controller annotation spring gives a feature of autodetection. We can add “component-scan” in spring-context and provide the base-package.

 <context:component-scan base-package="com.javapapers.spring.mvc" />  
 <mvc:annotation-driven />   
 

Then add @Controller annotation to controllers. The dispatcher will start from the base-package and scan for beans that are annotated with @Controller annotation and look for @RequestMapping. @Controller annotation just tells the container that this bean is a designated controller class.

@RequestMapping Annotation

@RequestMapping annotation is used to map a particular HTTP request method (GET/POST) to a specific class/method in controller which will handle the respective request.

@RequestMapping annotation can be applied both at class and method level. In class level we can map the URL of the request and in method we can map the url as well as HTTP request method (GET/POST).

We can use wildcard characters like * for path pattern matching.

In the following example, @RequestMapping(“/hi”) annotated at class level maps the request url and at again at lower level method level mapping is used for HTTP request mapping.

package com.javapapers.spring.mvc;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
@RequestMapping("/hi")
public class HelloWorldController {

	@RequestMapping(method = RequestMethod.GET)
	public String hello() {
		return "hello";
	}

	@RequestMapping(method = RequestMethod.POST)
	public String hi(@RequestParam("name") String name, Model model) {
		String message = "Hi " + name + "!";
		model.addAttribute("message", message);
		return "hi";
	}

}

Multi-action Controller

In a multi-action controller urls are mapped at method level since the controller services multiple urls. In below example two urls are serviced by the controller and they are mapped to separate methods.

package com.javapapers.spring.mvc;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class HelloWorldController {

	@RequestMapping("/")
	public String hello() {
		return "hello";
	}

	@RequestMapping(value = "/hi", method = RequestMethod.GET)
	public String hi(@RequestParam("name") String name, Model model) {
		String message = "Hi " + name + "!";
		model.addAttribute("message", message);
		return "hi";
	}

}

When using multi-action form controller there is a possibility of creating ambiguity in mapping the urls to methods. In those cases, if we have specified a
org.springframework.web.servlet.mvc.multiaction.MethodNameResolver it will be used to map a method. If a method name resolver is not specified then by default org.springframework.web.servlet.mvc.multiaction.InternalPathMethodNameResolver is used. This default implementation doesnot support wildcard characters.

When a matching method is not found, action will be mapped to a default method in the controller which does not have any @RequestMapping specified. If there are more such methods in the controller, then method name will be taken into consideration.

<beans ...>
 
 <bean 
  class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping" />
 
 <bean class="com.javapapers.spring.mvc.controller.HelloWorldController">
   <property name="methodNameResolver">
    <bean class="org.springframework.web.servlet.mvc.multiaction.PropertiesMethodNameResolver">
      <property name="mappings">
	<props>
	   <prop key="/">hello</prop>
	   <prop key="/hi">hi</prop>
	</props>
       </property>
     </bean>
    </property>
  </bean>
 
</beans>

@RequestParam Annotation

To bind the request parameter a variable in method scope this @RequestParam annotation is used.

In below code “name” is bound to the request parameter.

	public String hi(@RequestParam("name") String name, Model model) {
		String message = "Hi " + name + "!";
		model.addAttribute("message", message);
		return "hi";
	}

@ModelAttribute Annotation

An annotated method parameter can be mapped to an attribute in a model using @Modelttribute in controller. It can also be used to provide reference data for the model when used at method level.

@SessionAttributes, @CookieValue, @RequestHeader Annotation

We can declare session attributes used by a method handler using @SessionAttributes annotation in controller.

Similarly @CookieValue annotation is used to bind a method parameter to a HTTP cookie. In below example, a cookie with key “username” value will be bound to method variable name.

@RequestMapping("/hi")
public void userInfo(@CookieValue("username") String name)  {

  //...

}

Very similar to cookie binding, @RequestHeader is used to bind a header value to a method parameter.
Assume we have the following header value, and the following annotation in controller will bind the host variable to the value.
Host: localhost:8080

@RequestMapping("/hi")
  public void hostInfo(@RequestHeader("Host") String host)  {

  //...

}

This Spring tutorial was added on 11/09/2012.

Comments on "Spring Annotation Based Controllers" Tutorial:

  1. Arup says:

    Thanx for sharing you knowledge with us. Please keep sharing.I am a regular follower of your blog.

  2. Arvind says:

    i am new to this blog so i want to know what is the benefit of compiler and interpreter as java use both of them is there any major difference between compiler and interpreter i need detail explanation. i have to know i am waiting for my answer from past 3 years but i am not getting satisfied answer the main question rises in my mind like:-

    1. compiler and interpreter both converts a language from one level to another then witch one we have to use and why?

    2. is there any thing which can be achieved with interpreter but not with compiler or vice verse.

    3. And why java uses both if interpreter and compiler can achieve which is required by java then java designers can use double compiler or interpreter why both .

    Please tell me i am confused i don’t know whether my question is right or not.

  3. Anonymous says:

    very nice… Thanks Joe for sharing …

  4. Anonymous says:

    Now look this… one more in a good collection!! Good one Joe, Keep up posting!!

  5. Vishal says:

    I am a regular follower of your blog.Thanks for sharing please more share about @ModelAttribute Annotation at method level as well as perameter level

  6. Bala says:

    Good site to start with Basics.

  7. santosh says:

    nice. It helped me a lot to implement the complete annotation based controller…

    Thanks, Keep the good works up….

  8. hamid says:

    you raise our knowledge all the time by these great posts :)

  9. Pavan says:

    Above stuff is very helpfull in my project.

    Thanks, Keep the good works up….

  10. mithra says:

    Can u please tell about the spring restfull web services………?

  11. shrawan says:

    good article on spring MVC annotation.

  12. tSantosh says:

    very good Site…i like the content n info with itS look,,,too creative..*_*

  13. tSantoSh says:

    very good Site…i like the content n info with itS look,,,too creative..*_*

  14. sathya says:

    very nice

  15. Johan says:

    very helpful – thank you!

  16. Dhanya says:

    written well. Very much useful . keep posting more on spring.

  17. Mitaksh gupta says:

    can you please tell me how to set the cookie using spring framework..

  18. Nagaraju says:

    Am The Regular follower of your blog… please let me know how to make a single Spring3 controller to handle more than one request that are coming from different forms of same jsp… besides how to validate all the forms in that situation using annotations only?

  19. Shoaib Chikate says:

    Please ellobrate the example of @ModelAttribute
    and why we use in which senerio

  20. Tatarao voleti says:

    Nice article, It is very useful for me.
    Thank you Mr. Joe

  21. Freakyuser says:

    How does the Spring configurations work in general?
    Let us say that an application is run. What happens from here?
    Please explain step by step.
    The container looks for the context-path and what happens from there on?

    Thanks in advance.

  22. benudhar mansingh says:

    why used java annotation in spring & hibernate? what is its requirement & what is its advantages? can annotation make programmer easy for spring & hibernate?

  23. bhanuprasad says:

    nice tutorial

  24. Daya says:

    Hi Arvind,

    1)In java, compiler will convert .java code into byte code(class file) these byte code can be run in any operating system(i.e write once run any where)

    2)compiler: to produce byte code(class file)
    interpreter: to execute the byte code
    compiler cant do the interpreter task and vice-verse.

    3)Now we have byte code, in order to run byte code(class file) we require some thing called java interpreter(JVM)which is a specific implementation with respect to the Operating system, this byte code(class file)is picked by the interpreter to execute(run)

    interpreter will have it own set of instruction set, and we come to conclusion stating that interpreter is an instance of JRE

    please let me know if am wrong any where

    Awaiting for your kind response

    Thanks,
    Daya

  25. Hello says:

    Thanks

  26. karthik says:

    hi easy to understand.

  27. Jyoti says:

    Hi, nice tutorial. Very helpful.
    Thanks

  28. Manju Nath R says:

    Great article for beginners..

    Good GUI but not as much portable.

    Thank you!

  29. Harika says:

    Your blog is very useful,and also easy to understand. Thank you..

  30. Anonymous says:

    exlent

  31. namwade says:

    good

  32. Dsr says:

    Very good tutorial, thanks for sharing….
    I’ve a doubt in Multiaction Controller. I need to execute a function in the onload of all controller classes. So I created a base class which extends MultiactionController. But after that how will I define this common function so that all controllers that are extended this base class execute this function.

  33. krishna says:

    thank you very much. These stuff is very useful

  34. Anonymous says:

    excellent explanation…

  35. rakesh says:

    Really this is fantastic .If possible just do it for servlets , jsp and springs completely for all concepts with easy diagram and example with explanation.

    Thank you

  36. […] If you are a beginner, go through the Spring MVC tutorial before taking this. We will be using Spring 3 annotation based approach for the web […]

  37. Sudha says:

    It was excellent.
    Thank You so much

  38. Joe says:

    Thank you.

  39. […] For all these annotations (stereotypes), technically the core purpose is same. Spring automatically scans and identifies all these classes that are annotated with “ @Component, @Service, @Repository, @Controller”  and registers BeanDefinition with ApplicationContext. We read about @Controller in a previous Spring tutorial on annotation based controllers. […]

  40. kumaran says:

    Thankyou very much for your explaination in annotation based configuration.

    once again Thankyou!…………

  41. Arvind says:

    Hi daya,

    sorry for the late response i am glad to know that you have shown some interest in my question but please read these 3 points carefully again if you have ample time and then share your answer.you are correct for which you are trying to explain, i knew that but my this is not my question’s answer.

    Actually this is the point where my question starts.

    Thanks for the reply daya :)

  42. Samayan says:

    package Annotations;

    import java.util.List;
    import java.util.Map;
    //import net.roseindia.model.LoginForm;
    //import net.roseindia.service.MyService;

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.ModelAttribute;
    import org.springframework.web.bind.annotation.RequestMapping;

    @Controller
    public class AnnotationController {
    private MyService myService;

    @Autowired
    public void setMyService(MyService myService) {
    this.myService = myService;
    }

    @RequestMapping(“/loginForm.html”)
    public String loadForm(Map model) {
    return “loginForm”;
    }

    @ModelAttribute(“loginForm”)
    public LoginForm returnModel() {
    return new LoginForm();
    }

    @ModelAttribute(“countryList”)
    public List loadCounties() {
    return myService.loadCountry();
    }

    @RequestMapping(“/display.html”)
    public String responseForm(Map model, @Value() LoginForm loginForm) {
    if (loginForm.getLoginID() != “” && loginForm.getPassword() != “”){
    return “displayDetail”;
    }
    return “loginForm”;
    }

    }

  43. PrasadBabu says:

    simple and easy to understand…
    Thanks

  44. sandeep says:

    in spring container has its own init (),service() ,destroy() method.if then how it works.
    please clear my doubt.

    thanks

  45. Anonymous says:

    Compiler produces machine dependent code , which cannot be ported to all other machines to run. Where as in Java the interpreted code is compiled with the help of JVM and produce the machine dependent. Since JVM is specific to each platform, and due to the fact that it generates the machine dependent code Just when it is ready to run there is no problem of machine dependency. In order to achieve this write once run anywhere principle Java has both interpreter and compiler

  46. devendiran says:

    Thaks alot this tutorial now i got clear understanding about request handler and controller

  47. suresh says:

    CAn you please please give a full source code example with annotation
    so that i could get full idea
    i am close to nothing

    :(
    PLease help i have found only your site helpful

  48. Ganeshkumar says:

    Good tutorial

  49. sha says:

    Hi Joe,
    Can you please provide details how to implement
    form wizard in spring 3 MVC.

    Thanks,
    Sha.

  50. kirankumar says:

    Can u please tell me how to validate request parameters pattern

  51. Anjali says:

    @RequestMapping(value = “/get_list”,
    method = RequestMethod.GET,
    headers=”Accept=*/*”)

    Hi,

    I am getting error at headers. I have added all recent spring jars.

Comments are closed for this "Spring Annotation Based Controllers" tutorial.