Spring MVC - Configuring and Deploying the Application

Exclusive offer: get 50% off this eBook here
Spring Web Flow 2 Web Development

Spring Web Flow 2 Web Development — Save 50%

Master Spring's well-designed web frameworks to develop powerful web applications

$23.99    $12.00
by A P Rajshekhar | February 2010 | Java Open Source Web Development

In the previous discussion, the focus was on understanding the Model, View and Controller components of the application using Spring MVC framework. However, the developed components do not have knowledge of each other. Model is passed through Controller to the View using Logical View name. We have yet to map Logical View to the physical file. Also, to deploy the application, the application itself needs to be configured so that the Application Server knows to which component it should the route the requests. In this article by A. P. Rajshekhar, the focus will be on these two steps – configuring the components as well as configuring and deploying the application.

The first section will focus on configuring the application and its components so that the application can be deployed. The focus of the second section will be a real world application that will be developed using the steps described in the article on Developing the MVC components and in this article. That sets the agenda for this discussion.

Using Spring MVC – Configuring the Application

There are four main steps in configuring of the application. They are:

  1. Configure the DispatcherServlet
  2. Configure the Controller
  3. Configure the View
  4. Configure the Build Script

The first step will be same for any application that is built using Spring MVC. The other three steps change according to the components that have been developed for the application. Here are the details.

Configure the DispatcherServlet

The first step is to tell the Application server that all the requests for this (Spring MVC based) application need to be routed to Spring MVC. This is done by setting up the DispatcherServlet. The reason for setting up DispatcherServlet is that it acts as the entry point to the Spring MVC and thus to the application.  Since the DispatcherServlet interacts with the application as a whole (instead of individual components), its configuration or setting up at application level. And any setup that needs to be done at the application level is done by making the required entries in the web.xml.

The entries required  in the web.xml can be divided into the following:

  1. Servlet mapping
  2. URL mapping

The former specifies the details of the servlet and the latter specifies how the servlet is related to a URL. Here are the details.

Servlet mapping

Servlet mapping is akin to declaring a variable. It is through servlet mapping that Application Server knows which servlets of the application it needs to support.  Servlet mapping, in essence, assigns a name to a servlet class that can be reference throughout web.xml. To set up the DispatcherServlet, first it has to be mapped to a name. that can be done using <servlet-name> and <servlet-class> tags that are the child nodes of the <servlet> tag. The following statement maps the DispatcherServlet to the name "dispatcher".

<servlet>
<servlet-name>
dispatcher
</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
</servlet>

Since the DispatcherServlet needs to be loaded on the startup of the Application Server instead of the loading when a request arrives, the optional node <load-on-startup> with value of 1 is also required. The modified <servlet> tag will be:

<servlet>
<servlet-name>
dispatcher
</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>

Next step is to map the URL to the servlet name so that the requests can be routed to the DispatcherServlet.

URL mapping

Once the servlet has been mapped, the next step is to map the servlet name with a URL so that the requests for that particular URL can be passed on to the application via the DispatcherServlet. That can be done using the <servlet-name> and <url-pattern> nodes of the <servlet-mapping> node. The <servlet-name> is used to refer the name that was mapped with the DispatcherServlet class. The <url-pattern> is used to map a URL pattern with a servlet name so that when a request arrives matching the URL pattern, Application Server can redirect it to the mapped servlet. To map the DispatcherServlet with a URL pattern the <servlet-mapping> tag will be:

<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>

With this configuration/setting up of DispatcherServlet is complete. One point to keep in mind is that the URL pattern can be any pattern of one’s choice. However, it’s a common practice to use *.html for DispatcherServlet and *do for ActionServlet (Struts 1.x). Next step is to configure the View and Controller components of the application.

Mapping the Controller

By setting up the DispatcherServlet, the routing of requests to the application will be taken care of by the Application Server. However, unless the individual controllers of the application are setup/configured, the Framework would not know which controller to be called once the DispatcherServlet receives the request. The configuration of the Controller as well as the View components is done in the Spring MVC configuration file. The name of the configuration file is dependent on the name of the DispatcherServlet in web.xml, which is of the form <DispatcherServlet_name-servlet>.xml. So if the DispacherServlet is mapped to the name dispatcher, then the name of the configuration file will be dispatcher-servlet.xml. The file will reside in WEB-INF folder of the application.

Everything in Spring Framework is a bean. Controllers are no exceptions. Controllers are configured as beans using the <bean> child tag of <beans> tag. A Controller is mapped by providing the URL of the request as the name attribute and complete qualified name of the Controller class as the value of the class attribute. For example, if the request URL is say, http://localhost/test/hello.html, then the name attribute will have /hello.html and the value attribute will have the fully qualified class name say, org.me.HelloWorldController. The following statements depicts the same:

<bean name="/hello.html" class=" org.me.HelloWorldController "/>

One point to keep in mind is that the "/" in the bean name represents the relative path. In other words, /hello.html means that hello.html is directly under http://localhost/test. If hello.html was under another directory say, jsp which, in turn was directly under the application, then the name attribute will be /jsp/hello.html. Let us move onto configuring the Views.

Spring Web Flow 2 Web Development Master Spring's well-designed web frameworks to develop powerful web applications
Published: March 2009
eBook Price: $23.99
Book Price: $39.99
See more
Select your format and quantity:

Configuring the Views

The Controllers always returns the Logical View name and not its physical file name or address. The mapping of the Logical View to the physical file name or URL is done by providing the required entries in the Spring MVC configuration file.  Spring MVC uses Resolvers to match the logical name to physical file, process the file and provide the output to the user in desired format (html, PDF etc.). The mapping is done in following steps.

Declaring the Resolver

Resolver is declared using the <bean> tag. The id attribute is used to give the Resolver a name with which it can be referenced. The type of Resolver to be used is mapped to the name using the class attribute. The most commonly used Resolvers are:

  1. BeanNameViewResolver – resolves the bean class to the provided name
  2. JasperReportsViewResolver – It can be used when the logical view name maps to a JasperReports file
  3. InternalResourceViewResolver- It can be used for JSP and JSTL based views

For example, to map the View created in last part of this article, InternalResourceViewResolver can be used as it is JSTL based. The statement will be:

<bean id="viewResolver" 
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
</bean>

Specifying the Path

The path to the file is specified using the name and value attributes of <property> child tag of the <bean> tag. The path is passed on as prefix and suffix. Prefix specifies the path (or URL relative to the application) that can be appended before the file name and the suffix is the extension of the file that forms the View. For example, if the path to the file (including filename) is /jsps/HelloWorld.jsp, the suffix and prefix will be declared as follows:

<bean id="viewResolver" 
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name ="prefix" value ="/jsps/"/>
<property name = "suffix" value ="jsp"/>
</bean>

With that, configuration of the components comes to an end. Next, step will be about configuring/setting up the build script.

Configuring the build script

To configure the build script and build the application, two files need to be added or modified. They are:

  1. build.properties
  2. build.xml

The former is to specify the details such as location of server specific libraries including servlet-impl etc. The latter uses the former to substitute the location related details. The following section is not exhaustive in details about ant or build file.  So here are the details

build.properties

The main entries in that go into this file are the home directory of the application server and the second is the lib folder within the application server directory. The following statements do the same, the application server being tomcat and the OS being *nix (Unix/Linux).

appserver.home=/usr/share/tomcat5.5
appserver.lib=${appserver.home}/common/lib

build.xml

Apart from the other entries, the ones that are important for the compilation are <property> tag specifying the properties file name, <include> tag that specifies the libraries to be included, <fileset> tag specifying the path containing the include files. It as the value of dir attribute of the <fileset> that entries  that the build.properties come into play. The following statements tell the build environment which files from the app server files need to be included.

<path id="build.classpath">
<fileset dir="lib">
<include name="*.jar"/>
</fileset>
<fileset dir="${appserver.lib}"> <!-- servlet API classes: -->
<include name="servlet*.jar"/>
</fileset>
<pathelement path="${build.dir}"/>
</path>

That completes this section about configuring the components. Next section is about a real world example.

Spring MVC – In Real World

Now let us develop a simple application making use of the steps enumerated in first as well as this discussion. The functionalities of the application will be:

  1. Retrieve the list of logged-in users
  2. Display the list

In the first version of the implementation, we will populate the logged-in user list statically. That means the names in the list will be hard-coded for the current implementation. The files that will be the part of the application will be:

  1. LoggedInUsersController.java - it will retrieve the list of logged in users, create the model and pass it to the View.
  2. LoggedInUsers.jsp – Will display the model passed by the controller.
  3. web.xml – for setting up the DispatcherServlet
  4. spring mvc configuration – configuration for Controller and View
  5. build.properties – properties for the build file
  6. build.xml – defines the build configuration for the application

Let us get started. First is the controller.

public class LoggedInUsersController implements Controller { 
public ModelAndView handleRequest(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
List<String> strList = new List<String>();
strList.add("Ernest");
strList.add("Stan");
strList.add("Ram");
ModelAndView modelAndView = new
ModelAndView("LoggedInUsers");
modelAndView.addObject("list", strList);
return modelAndView;
}
}

Next comes the View.

<html>
<body>
<c:forEach items="${requestScope.list}"
var="currentName"
varStatus="status" >
User #<c:out value="${status.count}" /> is
<c:out value="${currentName}" /> <br />
</c:forEach>
</body>
</html>

Next is the web.xml. Only the relevant part is displayed here.

<servlet>
<servlet-name>
dispatcher
</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>

Next is the Spring MVC configuration file. The name of the file is dispatcher-servlet.xml.

<beans>
<bean name="/loggedInUsers.html" class=" org.me.LoggedInUsersController "/>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name ="prefix" value ="/jsps/"/>
<property name = "suffix" value ="jsp"/>
</bean>
</beans>

Next is the build.properties. Here again, the target app-server is tomcat and OS is Unix/Linux.

appserver.home=/usr/share/tomcat5.5
appserver.lib=${appserver.home}/common/lib

Lastly, build.xml.

<?xml version="1.0" encoding="UTF-8"?>
<project basedir="." default="build">
 
<property file="build.properties"/>
<property name="src.dir" value="src"/>
<property name="build.dir" value="classes"/>
 
<path id="build.classpath">
<fileset dir="lib">
<include name="*.jar"/>
</fileset>
<fileset dir="${appserver.lib}"> <!-- servlet API classes: -->
<include name="servlet*.jar"/>
</fileset>
<pathelement path="${build.dir}"/>
</path>
 
<target name="build">
<mkdir dir="${build.dir}"/>
<javac destdir="${build.dir}" source="1.5" target="1.5"
debug="true" deprecation="false" optimize="false" failonerror="true">
<src path="${src.dir}"/>
<classpath refid="build.classpath"/>
</javac>
</target>
 
<target name="clean" description="Clean output directories">
<delete>
<fileset dir="${build.dir}">
<include name="**/*.class"/>
</fileset>
</delete>
</target>
 
</project>

Summary

With that we come to the end of this discussion. What has been discussed here is just a glimpse of what Spring MVC can do. In the future each component of the will be discussed in detail starting with the Controller component. Till then...

If you have read this article you may be interested to view :

Spring Persistence with Hibernate Build robust and reliable persistence solutions for your enterprise Java application
Published: November 2009
eBook Price: $29.99
Book Price: $49.99
See more
Select your format and quantity:

About the Author :


A P Rajshekhar

 

A. P. Rajshekhar, Senior Developer with Vectorform, has worked on enterprise-level web applications and game development. His endeavors include development of a Learning Management System, a Supply Management Solution and Xbox-based games. He holds a Masters Degree in Computer Applications. He is a regular contributor to Devshed Portal on topics ranging from server-side development (JEE/.Net/RoR) to mobile (Symbian-based) development and game development (SDL and OpenGL) with a total readership of more than 1.4 million.

Contact A P Rajshekhar

Books From Packt

Spring Python 1.1
Spring Python 1.1

RESTful Java Web Services
RESTful Java Web Services

Spring 2.5 Aspect Oriented Programming
Spring 2.5 Aspect Oriented Programming

Spring Security 3 [RAW]
Spring Security 3 [RAW]

JasperReports 3.5 for Java Developers
JasperReports 3.5 for Java Developers

Apache CXF Web Service Development
Apache CXF Web Service Development

Apache Roller 4.0 – Beginner's Guide
Apache Roller 4.0 – Beginner's Guide

Groovy for Domain-Specific Languages
Groovy for Domain-Specific Languages

No votes yet

Post new comment

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
T
q
L
t
M
4
Enter the code without spaces and pay attention to upper/lower case.
Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software