☰ See All Chapters |
Spring Controller Interface
Controller is an Interface present in org.springframework.web.servlet.mvc package. It is the base and all controllers in spring should implement org.springframework.web.servlet.mvc.Controller interface. All built in controllers implement this Controller interface in direct or indirect way. Controller interface declares only one method, handleRequets(). The following snippet shows the signature of the handleRequest().
public ModelAndView handleRequest(HttpServletRequest req,HttpServletResponse res) throws Exception
handleRequest( ) method has to return ModelAndView class object. If handleRequest( ) method returns null then it informs the DispatcherServlet that response generation is complete and handleRequest( ) method is responsible for writing the response directly to HttpServletResponse. Hence when handleRequest( ) method returns null we can use this method as if it is doPost(), doGet() .
The SimpleControllerHandlerAdapter will support this Controller. Hence SimpleControllerHandlerAdapter will support all the controllers which implement Controller interface. SimpleControllerHandlerAdapter is default and we need not to configure this in spring configuration file. Hence for controllers which are of type Controller (Interface) we need not to configure any HandlerAdapters in spring configuration files.
Implementing Controller interface and including the request handling logic into handleRequest() method defines a very basic approach of handling the request. Generally we need to do request data conversion, binding the form data to the value object etc. To support these we use AbstractCommandController, SimpleFormController etc.
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.Controller;
public class DemoController implements Controller { @Override public ModelAndView handleRequest(HttpServletRequest arg0, HttpServletResponse arg1) throws Exception { String message = "Welcome to Spring MVC Applications."; return new ModelAndView("mypage", "welcomeMessage", message); } } |
AbstractCommandController (deprecated as of Spring 3.0)
If you want to process request parameters in the controller, then instead of using servlet classes to get request parameters in Abstract controller based controller, you can use AbstractCommandController which has the ability to auto populate request parameters to the data object which is also termed as command object in spring. This controller also offers feature to validate the request parameters.
AbstractController
It provides a basic infrastructure and all of Spring’s Controller inherit from AbstractController. It offers caching support, setting of the mime type etc. It has an abstract method ‘handleRequestInternal(HttpServletRequest, HttpServletResponse)’ which should be overridden by subclass.
The AbstractController is one of the most important abstract base controller providing basic features such as the generation of caching headers and the enabling or disabling of supported methods (GET/POST).
Example to demonstrate AbstractController
Project Directory Structure
home.jsp
<html> <head> </head> <body bgcolor="yellow"> Hello! <a href="welcome.do"><br> Click here to go to Welcome page</a> </body> </html> |
welcome.jsp
<html> <body bgcolor="pink"> ${welcomeMessage} </body> </html> |
DemoController.java
package com.java4coding;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.AbstractController; public class DemoController extends AbstractController { @Override protected ModelAndView handleRequestInternal(HttpServletRequest arg0, HttpServletResponse arg1) throws Exception { String message = "Hurray! </br>My first Spring MVC Applications."; return new ModelAndView("welcome", "welcomeMessage", message); } } |
welcome-servlet.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="https://www.springframework.org/schema/beans" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xmlns:context="https://www.springframework.org/schema/context" xsi:schemaLocation="https://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd https://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context-5.0.7.xsd">
<bean name="/pages/welcome.do" class="com.java4coding.DemoController" /> <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping" /> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/pages/" /> <property name="suffix" value=".jsp" /> </bean> </beans> |
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xmlns="https://java.sun.com/xml/ns/j2ee" xmlns:web="https://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="https://java.sun.com/xml/ns/j2ee https://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" id="WebApp_ID" version="2.4"> <servlet> <servlet-name>welcome</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>welcome</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app> |
Output
MultiActionController (deprecated in 4.3.3)
In Spring MVC application, org.springframework.web.servlet.mvc.multiaction.MultiActionController is used to group related/similar actions into a single controller and thus simplifying the application design by eliminating the separate controllers classes for each of the action.
In MultiActionController we can define more than one method each with different method name. Each method will handle separate request. These methods are hence called handler methods. These methods should have the following below signature.
As shown in the preceding code the method return type can be ModelAndView, Map or void.
If the return type is Map then the configured org.springframework.web.servlet.RequestToViewNameTranslator will be used to determine the view name, that is view name translation will be used to generate the view name. If return type is void then the return value is assumed as null, meaning that the handler method is responsible for writing the response directly to HttpServletResponse.
A String return value indicates the name of a view to be rendered without a specific model.
If return type is ModelAndView then MethodNameResolver is used, by defult AbstractUrlMethodNameResolver is used, if we want we can configure other MethodNameResolver.
Some MethodNameReolver implementations are
AbstractUrlMethodNameResolver
InternalPathMethodNameResolver
ParameterMethodNameResolver
PropertiesMethodNameResolver
In Spring Configuration file we have to configure mutilpe URL to a single controller, as given below:
Consider the following Controller,
public class CustomerController extends MultiActionController { public ModelAndView add(HttpServletRequest request, HttpServletResponse response) throws Exception {
} public ModelAndView delete(HttpServletRequest request, HttpServletResponse response) throws Exception {
} public ModelAndView update(HttpServletRequest request, HttpServletResponse response) throws Exception {
} } |
To above controller we can have mapping in Spring Configuration file as,
<beans> <bean id="mycontroller" class="com.java4coding.controller.CustomerController"/> <property name="mappings"> <props> <prop key="pages/add.htm">mycontroller</prop> <prop key="pages/delete.htm">mycontroller</prop> <prop key="pages/update.htm">mycontroller</prop> </props> </property> </bean> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/pages/"/> <property name="suffix" value=".jsp"/> </bean> </beans> |
Now, the requested URL will map to the method name in the following patterns:
pages/add.htmadd()
pages/delete.htmdelete()
pages/update.htmupdate()
All Chapters