Spring MVC Annotations

Annotations are introduced from the Java 5.o release. Annotations brought one of the major change to the Java programming style by eliminating the XML configurations and replaced with @ symbol annotations for everything. Since then, all the major Java frameworks have started implementing the annotations support for their release. Spring Framework has started using the annotations from the release Spring 2.5. This tutorial lists some of the mostly used annotations in the Spring MVC module. The following are the list of spring mvc annotations which is specific to the Spring MVC module:

  1. @Controller
  2. @InitBinder
  3. @RequestMapping
  4. @RequestParam
  5. @SessionAttributes

Declare Class As Controller Using @Controller

Prior to the Spring 2.5, the controller classes are declared in the spring configuration files. But, after the annotations style configurations, it is simplified by marking a class with @Controller annotation to tell the Spring container that this class is a controller. How spring knows that where is the controller classes are defined?. We have to add a simple line at the start of spring configuration file.


<context:component-scan base-package="package.name" />

The above declaration(context:component-scan) tells the Spring container to auto scan the entire package to identify the controller components. Basically this scan is not only for identifying the controller components, all the configurations are scanned and used by the container. If you are not specifying the package, spring will not scan your components and your application may not work.

Context / URI Using @RequestMapping

@RequestMapping is one of the important annotations which is used for defining the request urls based on the context root. Additionally this annotation specifies the expected HTTP request method for the request. This annotation can be define for class and methods. Look at the below example:


@Controller
@RequestMapping("/helloworld)
public class HelloWorld {
@RequestMapping(method = RequestMethod.GET)
public String getLogin(Map model) {
return "home";
}

}

In the above example, request mapping is used in the class level and method level. All the requests starting from “/helloworld” will be routed to this controller. getLogin method is accessed for the mapping url and if the HTTP method is GET. If the POST method is used, user would see the 404 page. If you are looking to have the requests like “/helloworld/id1″,  you can have the additional mapping in the method level. Like that any number of URI can be configured with each method having the different mappings.

@RequestParam and @SessionAttributes

@RequestParam is annotated in the methods to bind the method parameters to the request parameters. If the request is submitted by the browser, request parameters are passed through the URL query parameters. That can be easily mapped to the methods by annotating the method parameters with @RequestParam.

@Sessionattributes is used for passing the values across the different pages through the session. In simple terms, @SessionAttributes is replacement or simplified implementation for storing the values in the session object. If you look at the below example, you would understand how to use these two annotations.

SessionController.java

package javabeat.net.controller;

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

@Controller
@RequestMapping("/sessiontest")
@SessionAttributes("sessionValue")
public class SessionController {
	@RequestMapping(method = RequestMethod.GET)
	public String getForm(@RequestParam("param") String paramVal, ModelMap map){
		System.out.println("Param Value : " + paramVal);
		map.addAttribute("sessionValue", "Test Object");
		return "hello";
	}

}

hello.jsp

<%@ page contentType="text/html; charset=UTF-8" %>
<html>
<head>
<title>Hello World</title>
</head>
<body>
<%
	String value = (String)session.getAttribute("sessionValue");
	out.print(value);
%>
</body>
</html>

In the above code, sessiontest object is stored in the session and accessed in the JSP page. Note how the value is passed to the JSP page. Also check how the request param is mapped to the method parameter. The name of the parameter and @RequestParam parameter should be same. To test the above example, run the application and access it in the browser by adding the param query parameter.

@InitBinder – Use With Custom Validator

If you want to use the entire validation for the forms yourself using the spring custom validator, then you have to use @InitBinder annotation to bind the web form fields to the server side WebDataBinder component. For example, if you create a custom validator for performing the validations, that validator has to be binded using the @InitBinder annotations.


@InitBinder
 protected void initBinder(WebDataBinder binder) {

binder.setValidator(dateValidator);

}

In the above example, dataValidator is the custom validator for the data validations. Here I am not providing the complete details on how to write the custom validator. If you are not familiar about the spring validation, please read introduction to spring validation.

I hope this tutorial provided good overview on the list of annotations used in the spring mvc module. If you have any questions, please write it in the comments section.

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Comments

  1. hi sir,
    thank u very so much sir for ur nice explanation…

Speak Your Mind

*