Converting a Spring Controller into a @Controller

Login | Register

Converting a Spring Controller into a @Controller

Spring

In the Spring Web Framework, its typical to implement a Controller as a class that implements
org.springframework.web.servlet.mvc.Controller, for example:

public class InventoryController implements Controller {  
    public ModelAndView handleRequest(HttpServletRequest request, 
                        HttpServletResponse response)  
            throws ServletException, IOException {  
        // Handle the request here  
    }  
}

This class would then be defined within an application's Spring context XML file (typically appname-servlet.xml)

<bean name="/home.htm" class="springapp.web.InventoryController">  
    ...  
</bean>

Using Spring annotations however, its possible to remove the need to implement the
org.springframework.web.servlet.mvc.Controller and remove the bean definition within the XML file.

To change the Controller class to use annotations, the class needs to be annotated with the @Controller and @RequestMapping annotations as shown below. The method that will handle the request also needs to be annotated with the @RequestMapping. Note that this method no longer needs to confirm to the same signature as defined in org.springframework.web.servlet.mvc.Controller and now simply returns a ModelAndView instance.

@Controller 
@RequestMapping("/home.htm")  
public class InventoryController {  
  
    @RequestMapping(method=RequestMethod.GET)  
    public ModelAndView handleRequest() {  
        // Handle the request here  
    }
}

Now that we've redefined the Controller class, we can remove the bean definition from the application's context file. The final stage then to allow Spring to use the annotated Controller is to specify in the application's context file that we want to use annotations. This is achieved by adding the <annotation-driven /> element into the application context file.

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

About

At Develop In Java, we've been a part of the Java community for over 10 years. If there's anything you'd like us to cover, just ask !

Current versions

  • Java - 1.8
  • Java EE - 7
  • Spring - 4.x