Suggested Pages

Wednesday, May 9, 2012

Spring MVC - First Controller

In this post we are going to see how to write a simple controller in Spring using annotation support.

Step-1: Load Spring Servlet Context

First of all we have to declare the servlet of Spring that acts as a Front Controller. Besides we have to declare the URLs served by the DispatcherServlet.

<web-app version="2.4" xmlns:xsi="" xmlns="" xsi:schemalocation="">


Step-2: Create Controller class

In the following code there's a simple controller FirstController. The annotations involved in this class are:
  • @Controller : tells Spring that this class is a Controller
  • @RequestMapping on the class level means the controller serves the requests sent to this path: protocol://hostname:<port>/<context>/firstcontroller/
  • @RequestMapping on the method level means that the method serves the requests sent to this path: protocol://hostname:<port>/<context>/firstcontroller/method1

package com.simonefolinojavablog.spring.controller;

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

public class FirstController {
 public String processRequestMethod1(){
  return "example";

 public String processRequestMethod2(){
  return "example";


Step-3: Spring Context Configuration

In the web.xml we have specified spring-mvc.xml as the configuration file. In spring-mvc.xml we specify that we are going to use annotation support and the package to search for annotation as @Service,@Controller etc...
  • <context:annotation-config>:support to annotations
  • <context:component-scan base-package="com.simonefolinojavablog.spring.controller">: search the annotations as @Service, @Controller
  • InternalResourceViewResolver: special bean that makes possible to refer to Views using simply the name of JSP


<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<beans xmlns:xsi=""
 xmlns="" xmlns:context=""

 <context:annotation-config />

 <context:component-scan base-package="com.simonefolinojavablog.spring.controller" />

 <bean id="viewResolver"
  <property name="viewClass"
   value="org.springframework.web.servlet.view.JstlView" />
  <property name="prefix" value="/WEB-INF/pages/" />
  <property name="suffix" value=".jsp" />


Step-4: Create a JSP to redirect the web flow

The method of the FirstController returns example that is the name of the JSP to put in the directory WEB-INF/pages/example.jsp
<title>Landing Page</title>

<body>Hi, your first controller works fine!



Step-5: Client

Now we have to call the web application at the link http://localhost/${context}/firstcontrollert/method1.htm or http://localhost/${context}/firstcontrollert/method2.htm.
The controller redirects the web flow to example.jsp and you can see processRequestMethod1 or processRequestMethod2 in the console, depending on which method has served the request.

No comments :

Post a Comment

Suggested Pages