Converting a Spring Controller into a @Controller

DZone 's Guide to

Converting a Spring Controller into a @Controller

· Java Zone ·
Free Resource

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"> 
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.
public class InventoryController {

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 /> annotation into the application context file.
<?xml version="1.0" encoding="UTF-8"?> 
<beans:beans xmlns="http://www.springframework.org/schema/mvc"

<annotation-driven />


From http://www.davidsalter.co.uk/1/post/2011/04/converting-a-spring-controller-into-a-controller.html


Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}