Spring MVC Fast Tutorial: Hello, World!

We will:

  • create an Eclipse project
  • add Spring and some configuration code
  • create a controller class
  • run the project with Tomcat

Create a Maven project in Eclipse

  • In Eclipse, in the File menu, select New -> Project…
  • Under Maven, select Maven Project and click on Next >
  • Select the checkbox Create a simple project (skip archetype selection) and click on Next >
  • For the Group Id field, enter com.jeromejaglale. For the Artifact Id field, enter springwebapp. For Packaging, select war and click on Finish.

This generates a hierarchy of empty directories and pom.xml (Maven configuration file):

pom.xml
src
 |- main
  |- java
  |- resources
  |- webapp
 |- test
  |- java
  |- resources

Add Spring using Maven

In pom.xml, under <project>, define the Java and Spring versions, then add the dependencies for Servlet API, Spring Core and Spring MVC:

 
<properties>
	<java.version>1.8</java.version>
	<spring.version>4.1.6.RELEASE</spring.version>
</properties>
 
<dependencies>
 
	<!-- Servlet API -->
	<dependency>
		<groupId>javax.servlet</groupId>
		<artifactId>javax.servlet-api</artifactId>
		<version>3.1.0</version>
		<scope>provided</scope>
	</dependency>
 
	<!-- Spring Core -->
	<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>
 
<!-- boilerplate code allowing Maven to generate a .war archive without requiring a web.xml file -->
<build>
	<finalName>springwebapp</finalName>
 
	<plugins>
		<plugin>
			<groupId>org.apache.maven.plugins</groupId>
			<artifactId>maven-war-plugin</artifactId>
			<version>2.6</version>
			<configuration>
				<failOnMissingWebXml>false</failOnMissingWebXml>
			</configuration>
		</plugin>
	</plugins>
</build>

The declared dependencies (and their own dependencies) are automatically downloaded in the background by Eclipse. They are listed under Maven Dependencies in the left-hand side pane Package Explorer. Tomcat provides the Servlet API dependency, but we still declared it because our code will need it to compile. Maven will not include it in the .war file that we will generate later because of the scope tag with the provided value.

Create the configuration classes for Spring

  • Create the Java packages com.jeromejaglale.config and com.jeromejaglale.controller
  • In the com.jeromejaglale.config package, create the class AppConfig:
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = {"com.jeromejaglale.controller"})
public class AppConfig {
}

AppConfig is a Spring configuration class. It is a standard Java class annotated with:

  • @Configuration: This makes it a Spring configuration class
  • @EnableWebMvc: this enables Spring to receive and process web requests
  • @ComponentScan(basePackages = {“com.jeromejaglale.controller”}): this scans the package com.jeromejaglale.controller for Spring components
  • Also in the package com.jeromejaglale.config, create the class ServletInitializer:
public class ServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
	@Override
	protected Class<?>[] getRootConfigClasses() {
		return new Class<?>[0];
	}
 
	@Override
	protected Class<?>[] getServletConfigClasses() {
		return new Class<?>[]{AppConfig.class};
	}
 
	@Override
	protected String[] getServletMappings() {
		return new String[]{"/"};
	}
}

ServletInitializer is a configuration class for Spring's servlet; it replaces the standard web.xml file. How it works:

ServletInitializer implements these required methods:

  • getServletMappings(): defines the servlet root URI.
  • getServletConfigClasses(): declares the Spring configuration classes. Here, we declared our AppConfig class.

Create a controller class

In the package com.jeromejaglale.controller (which we declared in AppConfig), create the class HelloController and its method hi():

@Controller
public class HelloController {
	@RequestMapping("hi")
	@ResponseBody
	public String hi() {
		return "Hello, world.";
	}
}

Run the web application with Tomcat

  • In a terminal, at the root of the project folder, execute:
mvn clean install
  • A target folder will be generated with a springwebapp.war file in it.
  • Copy springwebapp.war to Tomcat's webapps folder.
  • Launch Tomcat (if it's not already running).
  • Go to http://localhost:8080/springwebapp/hi to check it's working.

Summary

We created a Maven project and added Spring to it. We created some configuration classes for Spring and a simple controller class.

The source code is available on GitHub.

Next: Build a Spring MVC web application
Previous: Installation on Mac OS
Up: Spring MVC Fast Tutorial

Feedback

thanks for this , using Maven needs to know the names of dependecies and this is hard
and the ServletInitializer is real boilerplate

complete with the bye Controller
package com.jeromejaglale.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class ByeController {
@RequestMapping("bye")
@ResponseBody
public String bye() {
return "AU REVOIR MON POTE, THE world IS YOURS.";
}

}
bernis
Jun 4, 2015
#1
nice
Amit
Aug 31, 2015
#2
Thank you, bernis. That additional feature helps complete my understanding of Spring.
larry
Sep 18, 2015
#3
Very good. Very thanks :)
Zeyad
Oct 22, 2015
#4
Created project in eclipse and followed the above steps except i have not used maven,instead i added just all the required JARs to lib folder.And i am getting below error-
HTTP status- 404 -/springwbeapp/hi
requested resource not available.

Please suggest , what could be the error
Akshay
Nov 14, 2015
#5
Hi,there's some error when access localhost:8080/springmvcapp/hi:

[org.springframework.web.servlet.PageNotFound] - No mapping found for HTTP request with URI [/springwebapp/hi] in DispatcherServlet with name 'SpringMVC'
/springwebapp/hi
Roy
Feb 8, 2016
#6
Hi, I got the same error as Roy. could you give us your opinion please.

thanks
zakaria
Mar 10, 2016
#7
In the controller class, could you try to add a slash at the beginning of the URL?

@RequestMapping("/hi")
Jérôme Jaglale
Mar 10, 2016
#8
Anyone could solve Roy's error?
krauss
Mar 31, 2016
#9
Hi for the 404 error change

Change the following line in ServletInitializer
from
return new String[]{"/"};
to
return new String[]{"/*"};

and in HelloController.java
change
@RequestMapping("hi")

to
@RequestMapping("/hi")
abhi
Apr 1, 2016
#10
Still getting the error after change @abhi
yelling
Jun 22, 2016
#11
Still does not work. It shows a directory listing.
Pat
Jun 22, 2016
#12
Hello, I still get the 404 after @abhi's suggestion.
GameTik
Aug 12, 2016
#13
To those who get a 404 error, what is your OS? Mac OS, Linux or Windows? Which version? Thanks.
Jérôme Jaglale
Aug 13, 2016
#14
macOS 10.12 using Tomcat 9.0.0.M10
sparky
Oct 6, 2016
#15