Spring MVC: Creating “Hello World” web application based on XML configuration

In this article, we will create simple “Hello World” web application using Spring MVC Framework. Learn Introduction to Spring Framework before proceeding with this example

This article and next coming articles for Spring MVC Framework, all are integrated with Maven for dependency resolution & packaging deployable war into the application server (this example uses Tomcat application server)

To create eclipse project for Spring MVC web application, go through this article (Maven + Eclipse + Spring application) which explains how to create empty skeleton with maven integrated for Spring project

Let’s us set-up environment for building sample “Hello World” web application

Technology Used

  • Java 1.7
  • Eclipse Kepler IDE
  • Spring-4.0.0-RELEASE
  • Apache Maven 3.0.4
  • Apache Tomcat 7.0.54

Mavenize or download required jars

Add Spring-4.0.0 dependencies to the pom.xml

	<dependencies>
		<!-- Spring dependencies -->
		<!-- for compile only, your container should have this -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>2.5</version>
			<scope>provided</scope>
		</dependency>

		<!-- JSTL tag library -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>

		<!-- Spring Core and Context -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<!-- Spring MVC -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${spring.version}</version>
		</dependency>
	</dependencies>

Folks who aren’t familiar with Maven concepts or don’t require maven for their project, can download the below jars individually from the spring site and include them in the classpath

Directory Structure

Before moving on, let us understand the directory/package structure once you create project in Eclipse IDE
Maven has to follow certain directory structure

  • src/test/java –> test related files, mostly JUnit test cases
  • src/main/java –> create source files under this source folder
  • src/main/resources –> all configuration files placed here
  • Maven Dependencies or Referenced Libraries–> includes jars in the classpath
  • WEB-INF under webapp –> stores web.xml & other configuration files
  • Create a package “com.spring.series.mvc.controller” under src/main/java folder

1_SpringMVC-XMLBased-Project-Structure

Web application:

For any web application, entry point is web.xml which describes how the incoming http requests are served or processed. Further, it describes about the global-context and local-context param (i.e.; <context-param> & <init-param>) for loading the files particular to project requirements & contains respective listener

With this introduction, we will understand how did we configured web.xml for this sample Spring MVC web application

web.xml (the entry point –> under WEB-INF)

Note: Normally, URI for any http request is looks like
http://<server>:<port>/<context-root>/<from_here_application_specific_path>

This web.xml file describes,

  • all http requests with wild card pattern “/” will be intercepted by the configured servlet called “DispatcherServlet” (org.springframework.web.servlet.DispatcherServlet)
  • </servlet-name> name mentioned in the web.xml is mvc-dispatcher, which on loading/exploading the war into the application server(Tomcat application server for our example) looks for the servlet filename called “mvc-dispatcher-servlet.xml”
  • <context-param> with its attributes describes the location of the file from where it has to be loaded
  • “mvc-dispatcher-servlet.xml” is the file which describes how exactly specific http requests are handled or which controllers gets invoked for certain http requests. We will see “mvc-dispatcher-servlet.xml” file for our Spring MVC web application

web.xml

<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">

	<!-- project display for web application -->
	<display-name>SpringMVC-XMLBased</display-name>

	<!-- welcome file list -->
	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>

	<!-- Spring MVC DispatcherServlet: dispatches HTTP requests to registered controllers -->
	<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>

	<!-- location of the root application context xml file -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
	</context-param>

	<!-- context loader listener -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

</web-app>

Dispatcher Servlet

Below mvc-dispatcher-servlet.xml file defines two beans,

  • bean with url pattern “/firstmvc.htm” will be intercepted by the respective controller defined i.e.; com.spring.series.mvc.controller.MyFirstMVController, this controller actually extends AbstractController
  • second bean basically defines the logic for view resolver i.e.; viewName returned by the Controller will be sandwiched between the prefix (WEB-INF/jsp) & suffix (.jsp)
  • Now, there should be a file under the directory as defined i.e.; (WEB-INF/jsp/<viewName>.jsp
  • Otherwise, not found exception thrown

mvc-dispatcher-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" 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-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">

	<!-- register beans for handling incoming HTTP requests -->
	<bean name="/firstmvc.htm" class="com.spring.series.mvc.controller.MyFirstMVController" />

	<!-- view resolver for rendering the final output -->
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix">
			<value>/WEB-INF/jsp/</value>
		</property>
		<property name="suffix">
			<value>.jsp</value>
		</property>
	</bean>
</beans>

Let’s see coding in action

 

My Controller

This is the actual request handler which is invoked from “DispatcherServlet” to service the incoming http request (with sample URL pattern http://localhost:8081/SpringMVC-XMLBased/firstmvc.htm)

  • Simple Java class extends AbstractController (org.springframework.web.servlet.mvc.AbstractController)
  • Override the method handleRequest which returns ModelAndView object which contains model data along with viewName (explained above)
  • modelAndView.addObject(“message”, “My First Spring MVC web application”); this is line which sets the message to be routed to the “DispatcherServlet” to display the data to the end user after resolving the viewName it got in the form of ModelAndView object

MyFirstMVController.java

package com.spring.series.mvc.controller;

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 MyFirstMVController extends AbstractController {

	// http://localhost:8081/SpringMVC-XMLBased/firstmvc.htm

	@Override
	protected ModelAndView handleRequestInternal(HttpServletRequest httpServletRequest,
			HttpServletResponse httpServletResponse) throws Exception {

		ModelAndView modelAndView = new ModelAndView("showMessage");
		modelAndView.addObject("message", "My First Spring MVC web application");
		return modelAndView;
	}
}

That’s all with the core part of the Spring MVC Framework; we will look into building a view to output the result to the end user after rendering it.

View Resolver: The JSP (Java Server Page)

  • simple JSP file to display the “message” to the end user, once entering http request
  • ${message} this is where the message will be outputted after rendering the result by the “DispatcherServlet”

showMessage.jsp (under WEB-INF/jsp)

<!DOCTYPE html>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html>
	<head>
		<meta charset="utf-8">
		<title>Welcome to Spring MVC Learnings</title>
	</head>
	<body>

<h2>${message}</h2>

	</body>
</html>

All efforts to see the below screen shot

  • Deploy the SpringMVC-XMLBased.war into the Tomcat application server
  • Start the Tomcat application server
  • Open the browser of your choice for example, chrome from Google
  • Enter the URL: http://localhost:8081/SpringMVC-XMLBased/firstmvc.htm
  • You will see the below rendered result

2_SpringMVC-XMLBased-direct-result

Other WAY

Earlier, we have entered the URL directly into the browser to view the rendered output but at times while building big enterprise application you need to flow through pages by clicking links. So here it is covered to show one such scenario

Steps to follow:

  • You have got index.jsp (under webapp folder) –> entering the URL http://<server>:<port>/<root_context> on the browser will displays the welcome page listed in the web.xml
  • index.jsp is designed to have a simple <a href=”firstmvc.htm”> link for page redirection
  • On clicking this link we have given the control to the controller after consulting DispatcherServlet.xml which redirects to the showMessage.jsp

index.jsp (under webapp)

<!DOCTYPE html>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<html>
	<head>
		<meta charset="utf-8">
		<title>Welcome</title>
	</head>
	<body>
		<a href="firstmvc.htm">My First Spring MVC Controller</a>
	</body>
</html>

Enter URL in the browser: http://localhost:8081/SpringMVC-XMLBased/
3_SpringMVC-XMLBased-index-link

You will see <anchor> links, which actually invokes the MyFirstMVController after consulting mvc-dispatcher-servlet.xml and returns the ModelAndObject object

Click the link <My First Spring MVC Controller>

The gotcha done!!

Now, see the rendered result

4_SpringMVC-XMLBased-index-result

Note: Nobody in practice use XML-Based configuration for Spring web application, otherwise you have got legacy application to maintain or else any specific project requirements.

Conclusion: We have seen a simple Spring MVC based web application using XML configuration. In the next article, we will see a much improved configuration-less annotation-based Spring MVC web application

Download project

Spring-MVC-XML-Based (3kB)

 

Read Also:

 

Happy Coding !!
Happy Learning !!

Spring MVC: Annotation based “Hello World” web application
Spring MVC - Creating Maven-based web application in Eclipse IDE