Spring MVC Controller Example
This is an example of Spring MVC Controllers. In Spring MVC, Controllers are used to provide access to the application behavior that is defined through a service interface. Controllers are the ones that interpret user input and transform it into a model that is represented to the user by the view.
Here we will create examples, making use of MultiActionController
and ParameterizableViewController
, two controller implementations provided by Spring. In order to do so, we will create a simple application with a view and a Controller in each case, and we will add all configuration necessary to run the application.
You may skip project creation and jump directly to the beggining of the example below.
Our preferred development environment is Eclipse. We are using Eclipse Juno (4.2) version, along with Maven Integration plugin version 3.1.0. You can download Eclipse from here and Maven Plugin for Eclipse from here. The installation of Maven plugin for Eclipse is out of the scope of this tutorial and will not be discussed. We are also using JDK 7_u_21. Tomcat 7 is the application server used.
Let’s begin,
1. Create a new Maven project
Go to File -> Project ->Maven -> Maven Project.
In the “Select project name and location” page of the wizard, make sure that “Create a simple project (skip archetype selection)” option is unchecked, hit “Next” to continue with default values.
Here the maven archetype for creating a web application must be added. Click on “Add Archetype” and add the archetype. Set the “Archetype Group Id” variable to "org.apache.maven.archetypes"
, the “Archetype artifact Id” variable to "maven-archetype-webapp"
and the “Archetype Version” to "1.0"
. Click on “OK” to continue.
In the “Enter an artifact id” page of the wizard, you can define the name and main package of your project. Set the “Group Id” variable to "com.javacodegeeks.snippets.enterprise"
and the “Artifact Id” variable to "springexample"
. The aforementioned selections compose the main project package as "com.javacodegeeks.snippets.enterprise.springexample"
and the project name as "springexample"
. Set the “Package” variable to "war"
, so that a war file will be created to be deployed to tomcat server. Hit “Finish” to exit the wizard and to create your project.
The Maven project structure is shown below:
- It consists of the following folders:
- /src/main/java folder, that contains source files for the dynamic content of the application,
- /src/test/java folder contains all source files for unit tests,
- /src/main/resources folder contains configurations files,
- /target folder contains the compiled and packaged deliverables,
- /src/main/resources/webapp/WEB-INF folder contains the deployment descriptors for the Web application ,
- the pom.xml is the project object model (POM) file. The single file that contains all project related configuration.
2. Add Spring-MVC dependencies
Add the dependencies in Maven’s pom.xml
file, by editing it at the “Pom.xml” page of the POM editor. The dependency needed for MVC is the spring-webmvc
package, as shown below:
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.javacodegeeks.snippets.enterprise</groupId> <artifactId>springexample</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>springexample Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> </dependency> </dependencies> <build> <finalName>springexample</finalName> </build> <properties> <spring.version>3.2.3.RELEASE</spring.version> </properties> </project>
3. Configure the application
The files that we must configure in the application are the web.xml
file and the mvc-dispatcher-servlet.xml
file.
The web.xml
file is the file that defines everything about the application that a server needs to know. It is placed in the /WEB-INF/
directory of the application. The <servlet>
element declares the DispatcherServlet
. When the DispatcherServlet
is initialized, the framework will try to load the application context from a file named [servlet-name]-servlet.xml
located in /WEB-INF/
directory. So, we have created the mvc-dispatcher-servlet.xml
file, that will be explained below. The <servlet-mapping>
element of web.xml
file specifies what URLs will be handled by the DispatcherServlet
.
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>Archetype Created Web Application</display-name> <servlet> <servlet-name>mvc-dispatcher</servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>mvc-dispatcher</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
The mvc-dispatcher-servlet.xml
file is also placed in WebContent/WEB-INF
directory. The org.springframework.web.servlet.view.InternalResourceViewResolver
bean is used as internal resource views resolver, meaning that it will find the jsp
and html
files in the WebContent/WEB-INF/
folder. We can also set properties such as prefix
or suffix
to the view name to generate the final view page URL. This is the file where all beans created, such as Controllers, will be placed and defined, as shown below:
mvc-dispatcher-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix"> <value>/WEB-INF/</value> </property> <property name="suffix"> <value>.jsp</value> </property> </bean> </beans>
4. Create the View
The view is a simple jsp page, placed in /WEB-INF/
folder. It shows the value of the attribute that was set to the Controller
.
helloWorld.jsp
<html> <html> <body> <h1>Spring 3.2.3 MVC</h1> <h3>The ${msg} method is invoked..</h3> </body> </html>
5. MultiActionController
MultiActionController
is an implementation of Spring, that allows multiple request types to be handled by the same class. Subclasses of this class can handle several different types of request with methods of the form :
public (ModelAndView | Map | String | void) actionName(HttpServletRequest request, HttpServletResponse response);
A Map
return value indicates a model that is supposed to be passed to a default view, whereas a String
return value indicates the name of a view to be rendered without a specific model.
5.1 XML configured Controller
The Controller
implementation below has two methods, that both return to the view a value, through the ModelAndView
.
HelloWorldController.java
package com.javacodegeeks.snippets.enterprise; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.multiaction.MultiActionController; public class HelloWorldController extends MultiActionController { public ModelAndView hello(HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView model = new ModelAndView("helloWorld"); model.addObject("msg", "hello()"); return model; } public ModelAndView goodBye(HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView model = new ModelAndView("helloWorld"); model.addObject("msg", "goodBye()"); return model; } }
In order to map the URL requests to the correct methods, MultiActionController
makes use of the Resolvers
. They are configured in the contoller bean definition in mvc-dispatcher-servlet.xml
file, inside the methodNameResolver
property. Here we shall see examples of three different resolver implementations provided by Spring.
5.1.1 InternalPathMethodNameResolver
This is the default implementation used by the MultiActionController
.
mvc-dispatcher-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix"> <value>/WEB-INF/</value> </property> <property name="suffix"> <value>.jsp</value> </property> </bean> <bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping" /> <bean class="com.javacodegeeks.snippets.enterprise.HelloWorldController"> <property name="methodNameResolver"> <bean class="org.springframework.web.servlet.mvc.multiaction.InternalPathMethodNameResolver"> </bean> </property> </bean> </beans>
We can now run the application. We first build the project with Maven. All we have to do is right click on the project and select -> Run As: Maven build. The goal must be set to package
. The war
file produced must be placed in webapps
folder of tomcat. Now we can start the server.
We’ll first call the hello()
method, hitting on :
localhost:8080/springexample/helloWorld/hello.htm
on a browser, and the result is the one shown below:
The result is the value that was passed to the ModelMap
in the method.
Next, let’s try calling the goodBye()
method:
localhost:8080/springexample/helloWorld/goodBye.htm
InternalPathMethodNameResolver
can make use of suffix
and prefix
attributes, that are applied to the initial URL request, so as to create the correct method name. For example, the below configuration will map requests like "/springexample/helloworld/hello.htm"
and "/springexample/helloworld/hello.htm"
to jcgHelloMessage()
and jcgGoodByeMessage()
methods of HelloWorldController
respectively.
mvc-dispatcher-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix"> <value>/WEB-INF/</value> </property> <property name="suffix"> <value>.jsp</value> </property> </bean> <bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping" /> <bean class="com.javacodegeeks.snippets.enterprise.HelloWorldController"> <property name="methodNameResolver"> <bean class="org.springframework.web.servlet.mvc.multiaction.InternalPathMethodNameResolver"> <property name="prefix" value="jcg" /> <property name="suffix" value="Message" /> </bean> </property> </bean> </beans>
5.1.2 ParameterMethodNameResolver
This resolver has a property to configure, whose name is set to paramName
and its value is set to action
.
mvc-dispatcher-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix"> <value>/WEB-INF/</value> </property> <property name="suffix"> <value>.jsp</value> </property> </bean> <bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping" /> <bean class="com.javacodegeeks.snippets.enterprise.HelloWorldController"> <property name="methodNameResolver"> <bean class="org.springframework.web.servlet.mvc.multiaction.ParameterMethodNameResolver"> <property name="paramName" value="action" /> </bean> </property> </bean> </beans>
When running this resolver case example, the resolver will map the URL request to the correct method, with the use of the action
parameter name.
Check out the two methods cases below:
5.1.3 PropertiesMethodNameResolver
This resolver maps URL requests to methods making use of properties as key-value pairs.
mvc-dispatcher-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix"> <value>/WEB-INF/</value> </property> <property name="suffix"> <value>.jsp</value> </property> </bean> <bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping" /> <bean class="com.javacodegeeks.snippets.enterprise.HelloWorldController"> <property name="methodNameResolver"> <bean class="org.springframework.web.servlet.mvc.multiaction.PropertiesMethodNameResolver"> <property name="mappings"> <props> <prop key="/helloworld/hello.htm">hello</prop> <prop key="/helloworld/goodBye.htm">goodBye</prop> </props> </property> </bean> </property> </bean> </beans>
When running the application, the resolver will map "/springexample/helloWorld/hello.htm"
requests to the hello()
method of HelloWorldController
and "springexample/helloWorld/goodBye.htm"
requests to the goodBye()
method of HelloWorldController
.
5.2 Annotations configured Controller case
An easy way to create a Controllers is with the use of annotations. The @Controller
annotation indicates that the class serves the role of a Controller
. The @RequestMapping
annotation is used to map a URL to either an entire class or a particular handler method. Here, it is used for both cases.
HelloWorldController.java
package com.javacodegeeks.snippets.enterprise; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.multiaction.MultiActionController; @Controller @RequestMapping("/helloworld/") public class HelloWorldController extends MultiActionController { @RequestMapping("hello.htm") public ModelAndView hello(HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView model = new ModelAndView("helloWorld"); model.addObject("msg", "hello()"); return model; } @RequestMapping("goodBye.htm") public ModelAndView goodBye(HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView model = new ModelAndView("helloWorld"); model.addObject("msg", "goodBye()"); return model; } }
Now, all that is needed in the mvc-dispatcher-servlet.xml
file, is to declare the context:component-scan base-package
tag, so that the container will scan the base package declared to search for annotated classes.
mvc-dispatcher-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"> <context:component-scan base-package="com.javacodegeeks.snippets.enterprise" /> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix"> <value>/WEB-INF/</value> </property> <property name="suffix"> <value>.jsp</value> </property> </bean> <bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping" /> </beans>
In this case the application runs as with the cases above.
6. ParameterizableViewController
ParameterizableViewController
is a Controller implementation that always returns a named view
. This controller offers an alternative to sending a request straight to a view such as a JSP. The advantage here is that the client is not exposed to the concrete view technology but rather just to the controller URL.
We create a new view, to use in this case:
page.jsp
<html> <body> <h1>Spring 3.2.3 MVC</h1> <h3>This is the ParameterizableViewController case..</h3> </body> </html>
Then, we can configure the mvc-dispatcher-servlet.xml
file, making use of the ParameterizableViewController
. It has a property with name
set to viewName
and value
set to the jsp page created above.
mvc-dispatcher-servlet
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix"> <value>/WEB-INF/</value> </property> <property name="suffix"> <value>.jsp</value> </property> </bean> <bean <bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"> <property name="mappings"> <props> <prop key="/hello.htm">helloController</prop> </props> </property> </bean> <bean name="helloController" class="org.springframework.web.servlet.mvc.ParameterizableViewController"> <property name="viewName" value="page" /> </bean> </beans>
Note that here we also make use of
SimpleUrlHandlerMapping
and ControllerClassNameHandlerMapping
classes, that were introduced in Spring MVC Handler Mapping Example.Now, run the application, with a URL request that will be mapped to this controller:
This was an example of Spring MVC Controllers.
Download the Eclipse project of this tutorial: SpringMVCControllerExample
This is the right blog for anybody who really wants to understand this topic.I am really thankful to the blog owner for help us by giving valuable study materials.