Spring MVC Sample Application Using XMl Config

Spring can be configured in two different ways: XML and Java Config. This article demonstrates how to create a simple Spring-MVC application using XML configuration files.


Create a New Maven Project

Considering that we are working with Eclipse, we can start with creating a new Maven Project to demonstrate our sample application. For detailed steps on how to create a New Maven Project using Eclipse refer to this article

Note: Alternatively, you can also create a new Dynamic Web Project and add all the dependencies to it. But we are using maven for our convenience because it allows us to define all dependencies in a pom.xml file and prevents the overhead of manually downloading and adding them to our project.

The directory structure generated by maven is shown below:

Directory Structure

Adding Dependencies with pom.xml

Shown below is the pom.xml file where we define our dependencies for using Spring MVC. We just need to add three dependencies for our sample application, highlighted below.

<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>cubearticle.examples</groupId>
  <artifactId>springmvc</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>springmvc Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
    	<groupId>javax.servlet</groupId>
    	<artifactId>javax.servlet-api</artifactId>
    	<version>3.0.1</version>
    </dependency>
    <dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-webmvc</artifactId>
	<version>4.1.4.RELEASE</version>
    </dependency>
    <dependency>
    	<groupId>jstl</groupId>
    	<artifactId>jstl</artifactId>
    	<version>1.2</version>
    </dependency>
  </dependencies>
  <build>
    <finalName>springmvc</finalName>
  </build>
</project>

All other related dependencies will be automatically discovered and included in the classpath by Maven.


Configuring DispatcherServlet in web.xml

DispatcherServlet is an essential part of Spring MVC application. All requests in Spring based web application should first pass through the DispatcherServlet. It acts as a 'front controller', which is responsible to delegate the request to other components of the web application.

The DispatcherServlet can be configured in the web.xml as shown below:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
    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_3_0.xsd" metadata-complete="false"> <display-name>Spring MVC</display-name> <servlet> <servlet-name>springWeb</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/springConfig/webConfig.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springWeb</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>/WEB-INF/pages/homePage.jsp</welcome-file> </welcome-file-list> </web-app>

webConfig.xml: Spring Configuration File

Every DispatcherServlet should be associated with its own Web Application Context. Spring initializes this Context and wires the beans using a configuration file, which can be configured in the web.xml shown in the above section.

The configuration file in our example is called as webConfig.xml, which is shown below:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc 
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd"> <mvc:annotation-driven /> <mvc:resources mapping="/resources/**" location="/resources/"/> <context:component-scan base-package="cubearticle" /> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/pages/" /> <property name="suffix" value=".jsp" /> </bean> </beans>

There are certain items that are declared in the configuration files which are required for the proper functioning of the Spring MVC based web application:

  • <mvc:annotation-driven/>: This is required to enable Spring MVC in our application. It creates certain beans that are used internally by Spring MVC framework.
  • <mvc:resources mapping="/resources/**" location="/resources/"/>: mvc:resources is used to set a default handler for static resources. It says that any url that starts with '/resources' should be handled by the servlet container's default servlet and Dispatcher servlet should not try to handle it itself. We can specify the location of our static resources using the location attribute.
  • <context:component-scan>: This tag is used to tell Spring to automatically discover and create beans. The 'base-package' attribute is used to specify the package where to look for beans.
  • We need to define a view resolver for our application. We have configured a InternalResourceViewResolver for our application. It applies the prefix and suffix to the logical view name to decide the actual view. For example if the logical view name is 'homePage', the actual view will be resolved as '/WEB-INF/pages/homePage.jsp'.

The Welcome Page: homePage.jsp

Shown below is the welcome page of our application. It shows a simple message and displays a form which asks the user for his name and a small message.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Welcome</title>
</head>
<body>
    Welcome to Spring MVC
    <br>
    <form action="hello" method="post">
	<label>Enter your name: </label><input type="text" name="user"><br>
	<label>Enter a short message: </label><input type="text" name="message"><br>
	<input type="submit" value="Submit">
    </form>
</body>
</html>

Controller

Shown below is our controller which will serve the request when the user enter's his name and a message.

@Controller
public class MyController {
    @RequestMapping(value="hello", method=RequestMethod.POST)
    public String sayHello(@RequestParam String user, @RequestParam String message, Model model){
        model.addAttribute("user", user);
        model.addAttribute("message",message);
        return "hello";
    }
}

The class is annotated with @Controller, which tells Spring to consider this class as a Spring Controller and create a bean for it. It is a specialized form of @Component.

The value attribute of @RequestMapping annotation specifies the request path this method will handle. The method attribute defines the HTTP method this method can handle.

The sayHello() method accepts 3 parameters. The parameters user and message are annotated with @RequestParam annotation. This is used to wrap the request paramaters in the method parameters. The user and message parameters passed from the form in the welcome page are captured in this method. A Model object is also passed as a parameter which is used to encapsulate the model data and send it over to the view. We add the form paramaters (user & message) in the model object, so that they can be extracted in the view.

Finally, the method returns a logical view name 'hello', which is resolved by the InternalViewResolver as /WEB-INF/pages/hello.jsp.


View: hello.jsp

Our view, hello.jsp is shown below which prints the user's name and the short message.

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
    <title>Hello World</title>
</head>
<body>
    <c:out value="${user}" /> says 
    <c:out value="${message}" />
</body>
</html>

The first line is a taglib declaration which imports the JSTL tag library. We would use JSTL to retrieve the name and the message from the model. Notice the use of EL (expression language) to extract the name and message value from the model object set in the controller.


Output

The image below shows the output of our Spring MVC Sample Application.

SQL MVC Output

Download Source Code

You can download the source code of the Sample Spring MVC Application discussed in this article.

POPULAR ARTICLES

Creating Conditional Beans in Spring

The concept of condition beans enables Spring to restrict the creation of any bean depending on the evaluation of a condition. These beans get created only when a preset condition is evaluated as true

View Article

Accepting Request Param and Path Variable in Spring Controller

Spring MVC provides various ways through which a client browser can pass data to the Controller. In this article we will discuss about accepting Request Parameters and Path Variables in Spring Contr..

View Article

Generate Namespace & Schema Information using JAXB

Most xml documents used in enterprise applications makes use of namespace to avoid element name conflicts. This article talks about generating these namespace and schema information when marshaling...

View Article

Switching Database Profile using Spring Profiles

We are most likely to have separate db configuration for different environment like development and production environment. Spring profiles provide a convenient way to switch db profiles at runtime.

View Article

SQL and its Sub-Languages

SQL (Structured Query Language) is a language understood by most modern databases. It is an ANSI (American National Standard Institute) standard language which is used to manipulate databases.

View Article

Introducing JUnit Rule

Junit Rules allows developers to add additional functionalities that can applied to all test methods in a test class. It is similar to the concept of custom test runners but with reduced restrictions.

View Article

Addressing Ambiguity in Spring Autowiring

Spring autowiring is powerful concept, but we should be very cautious while using it. We may end up in creating ambiguity while autowiring beans, which will cause autowiring to fail.

View Article

Creating and Using Synonym in Oracle Database

Synonyms are database objects used to provide duplicate names to existing objects in the database. It is just an alternate name used to hide the original name of the object.

View Article

Creating and Using Sequence in Oracle Database

A sequence is used to auto-generate numbers in ascending or descending order which can serve as a primary key or a part of it (in case of composite key).

View Article

Creating and Manipulating Constraints in Oracle Database

Constraints are used to impose certain rules on columns to avoid invalid data entry into the table. If any of the constraint is violated the operation fails.

View Article

Integrating Log4J with Perf4J for Performance Logging

Perf4j is an open source logging framework used primarily for monitoring performance statistics in java applications. Log4j has the ability to integrate with perf4j to capture performance data.

View Article

Tagging in GIT

Tagging allows us to mark a specific point in the commit history or snapshot. A tag is typically used to mark a project release. This article shows how to create tags in Git.

View Article