Spring MVC is one of the most popular Java framework used in developing web applications. It provides rich support for developing web applications.

In this article, we will learn how to create a simple Spring MVC Hello world example. Here, we are using Java configuration and JSP page to display the message to the user.

We are using Spring MVC 5 (5.1.4.RELEASE), Java 8 and Tomcat 8 Server for creating this application. We are using Eclipse IDE(Eclipse JEE Neon), with Eclipse Maven plugin support(m2e) to create Maven project.

We will follow the step by step approach for creating our application. Following are the steps to create our Spring MVC Hello world example.

  • Create a new Maven application and add the required dependencies.
  • Create a Web application configuration class.
  • Create a class to register Dispatcher servlet.
  • Create a Controller class to handle incoming requests.
  • Create a JSP page to display message to user.

Create a new Maven application and add the required dependencies

  • Create a new Maven application on your eclipse by selecting File > New > Maven Project on eclipse. Select the check box Create a simple project(Skip archetype selection) check box and click on Next as shown below. Make Sure that Maven installation for Eclipse plugin(m2e) is installed in your Eclipse IDE.
  • Fill the Group Id and Artifact ID fields with values com.asb and spring-mvc-app as shown in below image. Also select Packaging as war. This enables us deploy our war file on Tomcat server later. Finally, click on Finish button.
  • Above step will create a simple maven project architecture. We can add required dependencies for this created project by selecting the pom.xml file, right click > Open With > Maven POM Editor.
  • Next to add spring mvc dependencies to our application, Select Dependencies section, and click on Add button.
  • Under Select Dependency window, add the dependency information as shown below and click on OK button.
  • This will download required Spring Web MVC dependency jars and add it under project class path as Maven Dependencies library.
  • Add JSTL dependency by following the same step with Group Id : javax.servlet and Artifact Id : jstl Version : 1.2 and Scope : Compile.
  • Add servlet-api dependency by using Group Id : javax.servlet and Artifact Id : javax.servlet-api, Version : 3.1.0 and Scope : provided. Here, provided scope does not add the dependency jar while packaging the project into War file, as Tomcat will provide this jar while running the application on it.
  • Save the Pom.xml file. Now all the required dependencies are downloaded from Maven Central repository. Make sure that you have an active internet connection!!
  • Once the dependencies are downloaded, our Maven Dependencies library should have the following jars as shown in image below.
  • To add properties to Maven project, we can use Properties tab of Pom file’s Overview window, and Click on Create button. Enter the name and value fields and click on OK button as shown below. Here, we are adding maven.compile.source value to 1.8. Adding this property will make sure to use Java 1.8 to compile our application.
  • Also add another property with Name : maven.compiler.target and Value : 1.8
  • Also add the maven-war-plugin under build section by adding the following content to pom.xml file. Here, since we are not using Web.xml file, we have to set the <failOnMissingWebXml> property value to false, to get rid of the ‘web.xml file missing’ error.
<build>
  	<plugins>
  		<plugin>
  			<groupId>org.apache.maven.plugins</groupId>
  			<artifactId>maven-war-plugin</artifactId>
  			<configuration>
  				<failOnMissingWebXml>false</failOnMissingWebXml>
  			</configuration>
  		</plugin>
  	</plugins>
  </build>

Create a configuration class

Next step of the process is to create a Java configuration class as shown below. Create a WebConfig.java file as shown in below code snippet. Here, @Configuration annotation informs spring that it is a configuration class and treat it differently. It also informs spring that the class contains bean configurations(Annotated with @Bean annotation), these should be registered in spring application context.

Also notice the annotation @EnableWebMVC, this annotation imports the Spring Web MVC configurations. Our configuration class implements spring MVC’s WebMvcConfigurer configuration interface to enable custom configuration.

We are also registering a view resolver bean, by defining InternalViewResolver configuration. Internal view resolver is used to resolve the UI part of the application. In our example, We are adding JSTL View support by setting view class as JSTLView.class. We are also adding prefix (/WEB-INF/jsp/) and suffix (.jsp) to our view, which is returned by controller method. View resolver internally maps the views to src/main/webapp/WEB-INF/jsp/ and resolves the jsp page present inside the folder.

@ComponentScan annotation informs the Spring, that current package should be used as entry point for spring component scan. Which means that spring scans classes from current package recursively, and registers any class, defined with Spring annotations (Such as @Component, @Service, @Repository) and registers them as spring components.

package com.asb;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;

@Configuration
@EnableWebMvc
@ComponentScan(basePackages={"com.asb.controller","com.asb"})
public class WebConfig implements WebMvcConfigurer{

	@Override
	public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
		configurer.enable();
	}
	
	@Bean
	public InternalResourceViewResolver getInternalResourceViewResolver() {     
		InternalResourceViewResolver resolver = new InternalResourceViewResolver();      
		resolver.setViewClass(JstlView.class);     
		resolver.setPrefix("/WEB-INF/jsp/");      
		resolver.setSuffix(".jsp");      
		return resolver;
	} 
}

Create a class to register DispatcherServlet

Spring Web MVC framework follows MVC(Model View Controller) pattern, where all incoming HTTP requests are handled by a single front controller. Springs DispatcherServlet is a servlet, which handles all the incoming requests and maps them to corresponding handler methods based on the available request mapping.

In this following Dispatcher servlet configuration class(DispatcherServletInitializer.java), we are overriding default dispatcher servlet configurations by overriding
AbstractAnnotationConfigDispatcherServletInitializer class methods, to set our previously created servlet configuration class WebConfig.java.

We are also setting the servlet mapping to “/“, which means it maps all the incoming requests to controller classes based on provided request mapping.

package com.asb;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class DispatcherServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer{

	@Override
	protected Class<?>[] getRootConfigClasses() {
		return null;
	}

	@Override
	protected Class<?>[] getServletConfigClasses() {
		return new Class<?>[] {WebConfig.class};
	}

	@Override
	protected String[] getServletMappings() {
		return new String[]{"/"};
	}
}

Create a Controller class to handle requests

Now, our required configurations and DispatcherServlet is ready. Next step is to create controller class to handle incoming requests. Create a class HomeController.java as shown below, under package com.asb.controller. and add the following content. Here @Controller annotation tells the spring this is a controller class.

The welcome() method is defined with @RequestMapping annotation, which maps all the incoming requests to this method(notice the URL : “/”). This method has a Model parameter, which is used to carry all request parameters between Controller and view part. We are setting two attributes “greeting” and “message” with values “Hello” and “World”.

Finally, we are returning String value “welcome“. Spring MVC automatically converts this string to proper view by previously registered View Resolver by adding prefix and suffix(/WEB-INF/jsp/welcome.jsp) and renders proper view.

package com.asb.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class HomeController {
	
	@RequestMapping("/")
	public String welcome(Model model){
		
		model.addAttribute("greeting", "Hello");
		model.addAttribute("message", "World");
		
		return "welcome";
	}
}

Create a JSP page to display message

Final step is to create a simple view page, to render the message. Create a jsp page named welcome.jsp under src/main/webapp/WEB-INF/jsp/ (You have to create WEB-INF and jsp folders under src/main/webapp/ folder 🙂 )folder and add the following content.

Here, we are printing the model attributes “greeting” and “message“, which are added inside our controller method.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>Welcome</title>
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"> 
</head>
<body>
	<div class="bg-light" style="padding: 5%;">                      
		<h1> ${greeting} ${message} </h1>               
	</div> 
</body>
</html>

Run the application

Our first Spring MVC Hello World example application is ready to run!!. To Run our application on Tomcat server, Select the application > Right Click > Run As > Run on Server> Select the installed Tomcat server and Click on Finish. Our application will be now running at at : http://localhost:8080/spring-mvc-app/

Following will be the our Hello world jsp page saying Hello to the World..!! 🙂

That’s all about creating our simple Spring MVC Hello World example using Eclipse and Tomcat.

You may be interested in