Spring MVC Hello World example with Maven

In this article we will see how to create a "Spring MVC Hello World example with Maven" using Spring 5 and Java 8. We will also look into required maven dependencies and configurations.

Please make sure you have Java8+ and Maven 3+ already installed on your machine, spring 5 requires Java8+. In order to chek if Java8 is installed please follow the instructions below:

$ java -version

java version "1.8.0_181"
Java(TM) SE Runtime Environment (build 1.8.0_181-b13)
Java HotSpot(TM) 64-Bit Server VM (build 25.181-b13, mixed mode)


To ensure Maven 3+ is already installed, please follow the instructions below:

mvn --version

Apache Maven 3.5.2
Maven home: /usr/share/maven
Java version: 1.8.0_181, vendor: Oracle Corporation
Java home: /usr/lib/jvm/java-8-oracle/jre
Default locale: en_IN, platform encoding: UTF-8
OS name: "linux", version: "4.15.0-43-generic", arch: "amd64", family: "unix"


Step 1: Create a Java web project with maven

In order to create a Java web project with maven, follow the instruction given below:

mvn archetype:generate -DgroupId=com.tb.sample -DartifactId=SampleSpringProject -DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false

To make this project compitable with eclipse, dive into the created project directory and run following commands:

mvn eclipse:eclipse -Dwtpversion=2.0

Import this project into eclipse, using eclipse import wizard: File > Import > General > Existing Projects into Workspace

Step 2: Add required maven dependencies in pom.xml

SampleSpringProject/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.tb.sample</groupId>
	<artifactId>SampleSpringProject</artifactId>
	<packaging>war</packaging>
	<version>1.0-SNAPSHOT</version>
	<name>SampleSpringProject Maven Webapp</name>
	<url>http://maven.apache.org</url>
	<properties>
		<spring.version>5.1.3.RELEASE</spring.version>
		<jdk.version>1.8</jdk.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>2.5</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet.jsp</groupId>
			<artifactId>jsp-api</artifactId>
			<version>2.1</version>
			<scope>provided</scope>
		</dependency>
	</dependencies>

	<build>
		<finalName>SampleSpringProject</finalName>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.0</version>
				<configuration>
					<source>${jdk.version}</source>
					<target>${jdk.version}</target>
				</configuration>
			</plugin>
		</plugins>
	</build>

</project>

Step 3: Clean install Maven

Go to project directory and clean install maven to download dependencies and compile the project, using following command: mvn clean install mvn eclipse:eclipse -Dwtpversion=2.0

Step 4: Changes in web.xml

We will now add "DispatcherServlet" entry in web.xml, this will tell the container that all upcoming requests will be handled by spring with the help of configurations written in "mvc-dispatcher-servlet.xml".

SampleSpringProject/src/main/webapp/WEB-INF/web.xml

<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
  http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
	version="3.1">

	<display-name>Maven Project</display-name>
	<!-- Spring MVC -->
	<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>
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>  
            /WEB-INF/mvc-dispatcher-servlet.xml
        </param-value>
	</context-param>
</web-app>

What is Difference between "DispatcherServlet" and "ContextLoaderListener" ?

In Spring Web Applications, there are two types of container named "Application Context" and "Web Application Context", each of which is configured and initialized differently.

In the above web.xml file we have added two entries:

1) ContextLoaderListener


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

	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>  
            /WEB-INF/mvc-dispatcher-servlet.xml
        </param-value>
	</context-param>
Above entry will tell spring to load all files from the classpath that match "/WEB-INF/mvc-dispatcher-servlet.xml" and create an "Application Context" from it.

2) DispatcherServlet

Each DispatcherServlet defined in a Spring web application will have an associated WebApplicationContext. The initialization of the WebApplicationContext happens like this:

	<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>
The DispatcherServlet is an actual Servlet inherited from the HttpServlet base class, "/" indicates that all the requests coming to tomcat will be handled by "org.springframework.web.servlet.DispatcherServlet".

Step 5: Add spring configuration

In mvc-dispatcher-servlet.xml, we have added a "component-scan base-package" with value "com.techburps.*", this indicates that in order to resolve annotations like "@Controller", spring will look into child packages of "com.techburps" only.

The InternalResourceViewResolver resolves logical view name e.g. "home" to internal physical resources e.g. jsp files placed under WEB-INF folder.

SampleSpringProject/src/main/webapp/WEB-INF/mvc-dispatcher-servlet.xml

<?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:util="http://www.springframework.org/schema/util"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:cache="http://www.springframework.org/schema/cache"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
  http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
  http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd
  http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
  http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
  http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd">

	<context:component-scan
		base-package="com.techburps.*" />
	<mvc:annotation-driven />
	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix">
			<value>/WEB-INF/views/</value>
		</property>
		<property name="suffix">
			<value>.jsp</value>
		</property>
	</bean>
</beans>


Step 6: Add a Controller

@Controller, Indicates that an annotated class is a web controller, to be autodetected through classpath scanning. It is genrally used in combination with handler methods annotated by @RequestMapping.

@RequestMapping, maps HTTP requests to handler methods of MVC controllers, in this case a request for "/home" will be handled by "home()" method.

SampleSpringProject/src/main/java/com/techburps/controller/HomeController.java

package com.techburps.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class HomeController {

	@RequestMapping("/home")
	public ModelAndView home() {
		return new ModelAndView("home");
	}
}
We have returned an instance of "ModelAndView" from the annotated method, this will internally resolve "home" to actual physical location of resource (jsp) using "InternalResourceViewResolver", defined in "mvc-dispatcher-servlet.xml", i.e. "/WEB-INF/views/home.jsp". If the file is present at the resolved location JSP will be rendered on browser otherwise a "404" will return.

Step 7: Add a JSP

We have returned a jsp named "home" from our controller, lets add this to our project with a simple html showing "Hellow World" on the browser.

SampleSpringProject/src/main/webapp/WEB-INF/views/home.jsp

<html>
<body>
	<h2>Hello World!</h2>
</body>
</html>

Step 8: Test the project

Now we are done with adding all required files and configurations, the project structure should look like this:



Now run the project, and hit http://localhost:8080/SampleSpringProject/home in the browser, if everything went well you should see "Hello World" on the browser as shown below:




About The Author

Nagesh Chauhan

Nagesh Chauhan has 8+ years of software design and development experience in variety of technologies like - Core Java, Java 8 (Streams, Lambda), J2EE (Servlet, JSP), Spring Framework (MVC, IOC, JDBC, SECURITY etc), Spring Boot and Microservices, Kafla, Redis, Cassandra and Spark.