Meyyappan has posted 101 posts at DZone. View Full User Profile

Spring Annotation Based Controller Tutorial

06.15.2012
| 103833 views |
  • submit to reddit

In this example you will see how to develope annotation-based Spring controllers. This example is similar to the previous example except that it uses annotations. Here I will explain only the changes you need to make to the previous example, so if your a new to this go through the other example first.

If you are using annotations based controller then their is no need to extend any class or implement any interface. The only thing you need to do to make your simple java class to become a Spring controller is to add the @Controller annotation to it.

The following listing shows the UserController class.

package com.vaannila.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.vaannila.domain.User;
import com.vaannila.service.UserService;

@Controller
@RequestMapping("/userRegistration.htm")
@SessionAttributes("user")
public class UserController {

	private UserService userService;

	@Autowired
	public void setUserService(UserService userService) {
		this.userService = userService;
	}
	
	@RequestMapping(method = RequestMethod.GET)
	public String showUserForm(ModelMap model)	{
		User user = new User();
		model.addAttribute(user);
		return "userForm";
	}

	@RequestMapping(method = RequestMethod.POST)
	public String onSubmit(@ModelAttribute("user") User user) {
		userService.add(user);
		return "redirect:userSuccess.htm";
	}
	
}

The @Controller annotation is used to mark any java class as a controller class.

The @RequestMapping annotation is used to map the web request "/userRegistration.htm" to the UserController class.

The @SessionAttributes annotation is used to store the model object in the session. In our case the model object is user.

Using the @Autowired annotation the container can wire your beans automatically. By default autowire is done by type. Here any class that is compatible with UserService class will be chosen.

In the controller class you need to specify two methods, one for handling the HTTP GET request and the other for handling the HTTP POST request. These methods can have arbitrary names. When the form is first rendered the showUserForm() method will be invoked and when the form is submitted for processing the onSubmit() method will be invoked.

The @RequestMapping annotation is used to indicate the type of HTTP request.

The command object associated with the form is initialized in the showUserForm() method. The showUserForm() method has access to the ModelMap, in the showUserForm() method, create an instance of the command object and add it to the ModelMap. To add attribute to the ModelMap you can use the addAttribute() method. This method will automatically generate the attribute names for each element. In our case the user object will by default get the name as "user", you can also override the default value.

After the form is filled and submitted the onSubmit() method will be called. You can access the command object using the @ModelAttribute annotation. Here the command object name is user, the one that we set in the ModelMap. After getting the command object, call the service method to register the user and redirect the control to the "userSuccess.jsp" page.

Yes, here we redirect to the "userSuccess.htm" instead of just returning "userSuccess" this is necessary because if we simply return "userSuccess" the userSuccess.jsp page will be displayed, but when you refresh the page the form will be resubmitted, this is something that we don't want.

The "userSuccess.htm" request is mapped to the UserSuccessController class, here the redirect() method will be called and the control will be transferd to the userSuccess.jsp page.

The following code shows the UserSuccessController class.

package com.vaannila.web;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class UserSuccessController {

	@RequestMapping("/userSuccess.htm")
	public String redirect()
	{
		return "userSuccess";
	}
}

 To enable Spring to auto-detect the controllers you need to specify the base package of the controllers using the <context:component-scan> element in the Spring configuration file. DefaultAnnotationHandlerMapping and AnnotationMethodHandlerAdapter are preregistered in the web application context by default. But you need to explicitly register them, incase you have registered any other handler mappings or handler adapters explicitly.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context.xsd">


	<bean id="viewResolver"
		class="org.springframework.web.servlet.view. InternalResourceViewResolver"
		p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" />


	<bean id="userService" class="com.vaannila.service.UserServiceImpl" />

	<context:component-scan base-package="com.vaannila.web" />

	<bean class="org.springframework.web.servlet.mvc.annotation. DefaultAnnotationHandlerMapping" />

	<bean class="org.springframework.web.servlet.mvc.annotation. AnnotationMethodHandlerAdapter" />

</beans>

You can download and try the example here.

Source :Download
Source + Lib :Download
Published at DZone with permission of its author, Meyyappan Muthuraman.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Tags: