View RSS Feed

Spring Framework

Define a Controller in Spring MVC

Rate this Entry
by , 11-27-2011 at 11:17 PM (6817 Views)
When you work with Spring MVC, after configuring the Dispatcher Servlet in order to build an application you need to do the following:
Define controllers that invoke business logic and create a ModelAndView object.
Visualization component like JSP, Velocity or FreeMarker.
Annotation configuration or XML to wire the components together

The first thing that you will most likely do is to define a home page controller. Spring provides a number of controllers to use a base class for any controller that you want to create a controller that will meet your needs. There are listed below:
  • Process commands
  • Process shared actions
  • Redirect to static views
  • Provide servlet-like functionality
  • Handle forms
  • Provide wizard-like functionality to process multipage forms



So for almost any application, the home page’s main job is to welcome visitors and to display a handful of recent car promotions. So we use the HomeController, which is a basic Spring MVC controller that handles requests for the home page

Java Code:
package com.acme.springwebapp.web;

import java.util.Map;
import javax.inject.Inject;
import org.springframework.web.bind.annotation.RequestMapping;
import com.acme.springwebapp.service.CarService;

public class HomeController {
	public static final int DEFAULT_CARS_PER_PAGE = 5; 
	private CarService carService;
	
	@Inject public 
	HomeController(CarService carService) {
	this.carService = carService;
	} 
	
	@RequestMapping({"/","/home"}) 
	public String showHomePage(Map<String, Object> model) {
	model.put("cars", 
			carService.getCars(DEFAULT_CARS_PER_PAGE)); 
	return "home";
	}
}
There are a couple of things to note about HomeController, first the @Controller annotation indicates that this class is a controller class. It is a specialization of the @Component annotation that <context: component-scan> will pick up and register @Controller-annotated classes as beans. So we need to configure the <context:component-scan> in springexamples- servlet.xml so that the HomeController class (and all of the other controllers we’ll write) will be automatically discovered and registered as beans. This is shown below:

Java Code:
<context:component-scan base-package="com.acme.springexamples.web" />
The HomeController class will need to retrieve a list of the cars that are under promotion via the CarService. Therefore, the constructor has a CarService which is annotated with @Inject annotation in order that it is automatically injected when the controller is instantiated.

Submit "Define a Controller in Spring MVC" to Facebook Submit "Define a Controller in Spring MVC" to Digg Submit "Define a Controller in Spring MVC" to del.icio.us Submit "Define a Controller in Spring MVC" to StumbleUpon Submit "Define a Controller in Spring MVC" to Google

Categories
MVC , Controller , Spring 3

Comments