Spring 3.0 MVC Template Introduction

The following topics will be discussed in this article:

  • Downloading & Installing SpringSource Tool Suite (STS) Version: 2.8.1.
  • Setting up a Spring MVC Template project.
  • Deploying the packaged Hello World application.
  • A walk through of all Spring MVC Template components.

Downloading & Installing SpringSource Tool Suite (STS) Version: 2.8.1.
SpringSource Tool Suite (STS) can be downloaded for free from the Spring website: Spring STS Download
Note: For this example I am downloading springsource-tool-suite-2.8.1.RELEASE-e3.7.1-win32-installer.exe installed at C:\springsource using java version “1.6.0_16″. I followed the default installation options until complete.

Once the installation is complete launch STS. Close the welcome screen, your setup should look very similar to this:

Spring Source Tools Home Screen

Figure1: Spring Source Tools Home Screen

Setting up a Spring MVC Template project.
Next lets create an MVC Template project. In STS execute the following steps:

  1. Click on File –> New –> Spring Template Project. Select Spring MVC Project and click Next. (I set my project name to ‘SpringMVCTemplateProject’ and defined the top level package as ‘fm.devhub.myspringmvc’).
  2. You will see an alert notifying you to download the necessary resources, click Yes. What this will do is pull down the necessary libraries for your project to build correctly.

Note: Ensure your proxy settings are configured if you use one. Otherwise the files will not be able to download. You can set them by going to the Window menu –> Preferences –> General –> Network Connections.

STS New MVC Template Project

Figure 2: STS New MVC Template Project

Deploying the packaged Hello World application.
Next lets deploy and launch the application.

  1. Right click on the project and select Run As –> Run on Server.For this tutorial we are going to use VMware vFabric tc Server Developer Edition v2.6.
  2. Select the server and click Next. This screen indicates that the server is selected and that your project is configured to be deployed. Click Finish.
Run On Server

Figure 3: Run On Server

The first attempt at starting the server yielded the following error for me, if you didn’t receive any errors then skip over this section.

http://localhost:8080/SpringMVCTemplateProject/
HTTP Status 404 - 

------------------------------------------------------

type Status report

message 

description The requested resource () is not available.

------------------------------------------------------

VMware vFabric tc Runtime 2.6.1.RELEASE/7.0.20.B.RELEASE

WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/SpringMVCTemplateProject/] in DispatcherServlet with name appServlet'

In order to fix the error above right click on the webapp directory in your project explorer and select Build Path –> Click Use as Source Folder. What this does is add the webapp directory to the build path which ensures our webapp files are included in the deployment. I haven’t had much time to find out exactly why this problem is occurring out of the box, so if you know the root cause please leave a comment.

Once the error is resolved repeat the steps above to deploy the application (if you didn’t encounter any errors then ignore this step). You should see the following screen indicating that everything is working correctly:

Successful Spring MVC Template Deploy

Figure 4: Successful Spring MVC Template Deploy

Now that the application is up and running we can proceed to the next section in this tutorial.

A walk through of all Spring MVC Template components.
In this section we will dissect most of the files provided in the Spring MVC Template project.

STS Spring 3.0 MVC Template Project Explorer

Figure 5: STS Spring 3.0 MVC Template Project Explorer

In order to see the package explorer (as displayed in the picture above) in your STS IDE, you will need to switch the perspective from Java EE to Java.

HomeController.java

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package fm.devhub.myspringmvc;
+import java.text.DateFormat;
/**
* Handles requests for the application home page.
*/
@Controller
public class HomeController {
    private static final Logger logger =
LoggerFactory.getLogger(HomeController.class);
    /**
  * Simply selects the home view to
* render by returning its name.
  */
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String home(Locale locale, Model model) {
        logger.info("Welcome home! the
client locale is "+ locale.toString());
        Date date = new Date();
        DateFormat dateFormat =
DateFormat.getDateTimeInstance(DateFormat.LONG,
DateFormat.LONG, locale);
        String formattedDate = dateFormat.format(date);
        model.addAttribute("serverTime", formattedDate );
        return "home";
    }
}

Line 8:
The @Controller annotation defines the class as a controller. Controller classes in Spring are used to prepare the model that will be mapped to a view for a particular resource.

In the code above we have a Model object (line 17) called model, and we are adding an attribute to it called ‘serverTime’ (line 25). What this does is pass the model to our ‘home’ View which is our home.jsp, and if you look at the home.jsp code, you will see that we are printing the Model attribute ‘serverTime’.

Line 16:
@RequestMapping is used to map an HTTP Request to a specific resource. In this case we are mapping http://localhost:8080/SpringMVCTemplateProject/ as denoted by value = “/” to our HomeController.java’s home method, which returns control to home.jsp.
Therefore any request comming in via localhost:8080/SpringMVCTemplateProject/ will get returned to home.jsp when line 27 is reached.

Method = RequestMethod.GET is specifying the HTTP method ‘GET’ vs. ‘POST’ for example.
Note: To understand HTTP Methods better you can read the post “HTTP Request/Response” under Web Development Basics.

Line 17:
public String home(Locale locale, Model model) is the a method that gets called when this request comes in:
@RequestMapping(value = “/”, method = RequestMethod.GET).

The name itself ‘home’ is an arbitrary name that the developers who created the Spring MVC Template chose to use. If you change the name to homepage for example, the application will still deploy correctly. Just as the method name ‘home’ is arbitrary, as are the arguments being passed “Locale local, Model model” we could choose to pass additional arguments if we wanted.

Keep in mind that the Spring MVC Template is setup to be as simple and re-usable/extendable as possible, hence the reason why its using only the most basic of Spring MVC’s features.

Line 25:
model.addAttribute(“serverTime”, formattedDate ) is basically setting an attribute that will be accessible to our home.jsp (our view). And that attribute is ‘serverTime’.
If you look at home.jsp line 12 you can clearly see the link:

The time on the server is ${serverTime}.

Line 27:
Return ‘home’ is basically returning to our home.jsp view. If you were to modify HomeController.java to return “home1″ for example, you will get an error saying that Spring cannot locate the resource. Likewise if you change the name of the file to home1.jsp without updating the HomeController, you will receive an error.

servlet-context.xml

XHTML
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<?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"
    xmlns:context="http://www.springframework.org/schema/context"
    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
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
    <!-- DispatcherServlet Context: defines this servlet's
request-processing infrastructure -->
    
    <!-- Enables the Spring MVC @Controller programming model -->
    <annotation-driven />
    <!-- Handles HTTP GET requests for /resources/** by
efficiently serving up static resources in
the ${webappRoot}/resources directory -->
    <resources mapping="/resources/**" location="/resources/" />
    <!-- Resolves views selected for rendering by @Controllers
to .jsp resources in the /WEB-INF/views directory -->
    <beans:bean
class=
"org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<context:component-scan base-package="fm.devhub.myspringmvc" />
</beans:beans>

Lines 2-9:
Defining the namespace and schema for the Spring servlet context file version 3.0.

Line 10:

Line 13:
Enables Spring 3.0 MVC annotations, we have used a few of them already such as @Controller and @RequestMapping. Some others include @SessionAttributes, @ModelAttribute and @InitBinder.

Line 14-16
Here mvc:resources tag is being declared although it isn’t currently being used. What the resources tag does is declare a ‘resource’ directory where you would want your publicly accessible static files to reside. An example would be JavaScript files, images, etc. One of the benefits of utilizing this tag is that you can specify browser caching settings in order to reduce the number of requests for resources being sent to your server.

If you look at your Package Explorer, you can see Spring MVC Template has this folder created under webapp –> resources.

Line 19:
This is the declaration of a ViewResovler, this is basically the Spring component that defines the rules of how to match or resolve an HTTP Request with a View. so if we look at the code we can see that we are using the “InternthealResourceViewResolver”
we are defining the prefix as “/WEB-INF/views/”
and the suffix as ‘.jsp’
So, when HellowController.java returns ‘home’, the ViewResolver resolves the view by saying you want to look in “/WEB-INF/views/” and the file type is ‘.jsp’ so append ‘.jsp’ to the name. In term we end up with path and name of the file ‘View’ that we want which ends up being ‘/WEB-INF/views/home.jsp’

Keep in mind that there are many different types of View Resolvers, such as VelocityViewResolver, UrlBasedViewResolver, ResourceBundleViewResolvIemrplementation and XmlViewResolver. The MVC Spring 3.0 documentation defines InternthealResourceViewResolver as: A “Convenient subclass of UrlBasedViewResolver that supports InternalResourceView (in effect, Servlets and JSPs) and subclasses such as JstlView and TilesView. You can specify the view class for all views generated by this resolver by using setViewClass(..).”

Line 20:
The prefix is basically where to locate the files

Line 21:
The suffix is basically the file type, in our case a .jsp.

Line 23:
component-scan is basically enabling a feature in Spring 3.0 which will automatically search for annotated classes and register their BeanDefinitions to the Application Context. This is simply an alternative to explicitly declaring the configuration in the application context xml.

root-context.xml

XHTML
1
2
3
4
5
6
7
8
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    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">
    
    <!-- Root Context: defines shared resources visible to all other web components -->
        
</beans>

Lines 2-4:
Defines the namespace and schema for spring beans version 3.0.
Line 6:
Here we would have all shared resources for our application defined. For example a hibernate connection, or global bean values which need to be declared at startup.

home.jsp

XHTML
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" %>
<html>
<head>
    <title>Home</title>
</head>
<body>
<h1>
    Hello world!
</h1>
<P> The time on the server is ${serverTime}. </P>
</body>
</html>

Line 1:
Is the declaration of our JSP taglibrary. Specifically JSTL1. I recommend reading more about JSTL if you have the time.

Lines 3-11:
The body of our home.jsp.

Line 12:
Here is where we use the Model attribute (serverTime) which was added in HomeController.java and display it to the user.

web.xml

XHTML
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring/root-context.xml</param-value>
    </context-param>
    
    <!-- Creates the Spring Container shared by all Servlets and Filters -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <!-- Processes application requests -->
    <servlet>
        <servlet-name>appServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
        
    <servlet-mapping>
        <servlet-name>appServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

Lines 2-4:
Defines the namespace and schema for web-app version 2.5.

Lines 7-10:
Defines the ‘contextConfigLocation’. root-context.xml can be used to define Spring beans which are global to all Servlets. This could be useful for a database configuration for example.

Lines 13-15:
Adds a global context listener Spring. It basically can be viewed as initializing the Spring framework upon our web application start-up.

Lines 18-26:
A very important component of spring is the DispatcherServlet (look at Figure 6). The DispatcherServlet basically manages the request/response workflow between our controllers and views. It is a core component of how Spring MVC works.

Lines 28-31:
Adds our application servlet arbitrarily named appServlet.

Below is a visual representation of the application flow for our Spring 3.0 MVC Template hello world application.

Figure 6: Spring3.0 MVC Template Request/Response Flow

Figure 6: Spring3.0 MVC Template Request/Response Flow

Thanks for reading! If you find any technical inaccuracies or deficiencies in this article, please make devhub.fm aware by posting a comment. Any feedback is welcome & encouraged.