Spring MVC Hello World Example

Spring MVC is one of the most popular Java frameworks in developing web applications. It provides rich support for developing web applications. Let’s create a classic spring MVC hello world example application.

In this article, we will learn how to create a simple Spring MVC web application. 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 the Eclipse IDE(Eclipse JEE Neon) with the Eclipse Maven plugin support(m2e) plugin to create the Maven project.

Creating the Spring MVC Hello world application

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.

Also, make Sure that Maven installation for the Eclipse plugin(m2e) is available in your Eclipse IDE.

spring mvc example

Fill the Group Id and Artifact ID fields with values com.asb and spring-mvc-app as shown in the below image.

Also, select Packaging as war. This enables us to deploy our war file on the Tomcat server later. Finally, click on the Finish button.

image 2

Adding the maven dependencies

The above step will create a simple maven project architecture. We can add the required dependencies for this project by selecting the pom.xml file, right-click > Open With > Maven POM Editor.

Next, to add spring MVC dependencies to our application. Select the Dependencies section, and click on Add button.

Finally, under the Select Dependency window, add the dependency information and click on the OK button.

The maven downloads the required Spring Web MVC dependency jars and adds them under the project classpath as Maven Dependencies library.

image 3

Add the JSTL dependency by following the same step with Group Id: javax.servlet and Artifact Id: jstl Version: 1.2 and Scope: Compile.

Also, add the servlet-api dependency. Here, the provided scope does not add the dependency jar while packaging the project into the War file, as Tomcat will provide this jar while running the application on it.

Finally, save the pom.xml file.

We can observe the Maven Dependencies library as shown in the image below.

spring mvc hello example

To add properties to the Maven project, we can use the Properties tab of the Pom file’s Overview window 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.

spring mvc

Also, add another property with Name: maven.compiler.target and Value: 1.8

Finally, add the maven-war-plugin under the build section by adding the following content to the pom.xml file.

The <failOnMissingWebXml> property with the value to false gets 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

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

The @EnableWebMVC 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 the InternalViewResolver configuration. An internal view resolver resolves 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 a prefix (/WEB-INF/jsp/) and suffix (.jsp) to our view, which is returned by the 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 to use the current package as an entry point for spring component scan. This means that spring scans classes from the 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 and a single front controller handles all incoming HTTP requests.

Springs DispatcherServlet 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

The next step is to create a 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 the Controller and view part. We are setting two attributes “greeting” and “message” with values “Hello” and “World”.

Finally, we are returning the 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 the 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

The 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>

Running spring mvc hello world example application

Our first Spring MVC Hello World example application is ready to run!!. To run our application on the 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 http://localhost:8080/spring-mvc-app/

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

spring mvc

Conclusion

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