Spring MVC Hello World Project Example
By: Ramesh Fadatare
Tags: Spring Mvc, Spring

In this article, we will learn how to create a simple Hello World Spring MVC Application using Spring MVC 5 +, JSP, Maven build tool, and Eclipse IDE.

In this example, we will use a Java-based configuration that is we configure the Spring DispatcherServlet and spring beans configuration using all Java Code (no XML).

Before you get started, check out Spring Data JPA Tutorial and Spring MVC Tutorial

Related Spring MVC Tutorials and Articles

Tools and technologies used

Spring MVC — 5.1.0 RELEASE

JDK — 1.8 or later

Maven — 3.5.1

Apache Tomcat — 8.5

IDE — STS/Eclipse Neon.3

JSTL — 1.2.1

1. Create Maven Web Application

Let’s create a Maven-based web application either using a command line or from Eclipse IDE.

1. Use Guide to Create Maven Web Application link to create a maven project using a command line.

2. Use Create Maven Web Application using Eclipse IDE link to create maven web application using IDE Eclipse.

Once you created the maven web application, refer to pom.xml file jar dependencies.

2. Add Dependencies — pom.xml File

Refer to the following pom.xml file and add jar dependencies to your pom.xml.



xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://maven.apache.org/maven-v4_0_0.xsd">

<modelVersion>4.0.0</modelVersion>

<groupId>net.javaguides.springmvc</groupId>

<artifactId>springmvc5-helloworld-exmaple</artifactId>

<packaging>war</packaging>

<version>0.0.1-SNAPSHOT</version>

<name>springmvc5-helloworld-exmaple Maven Webapp</name>

<url>http://maven.apache.org</url>

<properties>

<failOnMissingWebXml>false</failOnMissingWebXml>

</properties>

<dependencies>

<!--

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-webmvc</artifactId>

<version>5.1.0.RELEASE</version>

</dependency> 4.0.0 net.javaguides.springmvc springmvc5-helloworld-exmaple war 0.0.1-SNAPSHOT springmvc5-helloworld-exmaple Maven Webapp http://maven.apache.org false org.springframework spring-webmvc 5.1.0.RELEASE <!-- JSTL Dependency -->

<dependency>

<groupId>javax.servlet.jsp.jstl</groupId>

<artifactId>javax.servlet.jsp.jstl-api</artifactId>

<version>1.2.1</version>

</dependency>

<dependency>

<groupId>taglibs</groupId>

<artifactId>standard</artifactId>

<version>1.1.2</version>

</dependency> <!-- Servlet Dependency -->

<dependency>

<groupId>javax.servlet</groupId>

<artifactId>javax.servlet-api</artifactId>

<version>3.1.0</version>

<scope>provided</scope>

</dependency> <!-- JSP Dependency -->

<dependency>

<groupId>javax.servlet.jsp</groupId>

<artifactId>javax.servlet.jsp-api</artifactId>

<version>2.3.1</version>

<scope>provided</scope>

</dependency>

</dependencies>

<build>

<sourceDirectory>src/main/java</sourceDirectory>

<plugins>

<plugin>

<artifactId>maven-compiler-plugin</artifactId>

<version>3.5.1</version>

<configuration>

<source>1.8</source>

<target>1.8</target>

</configuration>

</plugin>

</plugins>

</build>

</project>

Note that we are using spring-webmvc dependency for a Spring MVC web application.

Next, let’s create a standard project structure, please refer below diagram.

3. Project Structure

Standard project structure for your reference -

As the name suggests Spring MVC, look at the diagram we are using the Model-View-Controller approach.

Model — HelloWorld.java

View — helloworld.java

Controller — HelloWorldController.java

Next step, we will configure Spring beans using Java-based configuration.

4. Spring Configuration — AppConfig.java

Create an AppConfig class and annotated with @Configuration, @EnableWebMvc, and @ComponentScan annotations as follows.

package net.javaguides.springmvc.helloworld.config; 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.EnableWebMvc;

import org.springframework.web.servlet.view.InternalResourceViewResolver;

import org.springframework.web.servlet.view.JstlView; /**

* @author Ramesh Fadatare

*/ @Configuration

@EnableWebMvc

@ComponentScan(basePackages = {

"net.javaguides.springmvc.helloworld"

})

public class AppConfig { @Bean

public InternalResourceViewResolver resolver() {

InternalResourceViewResolver resolver = new InternalResourceViewResolver();

resolver.setViewClass(JstlView.class);

resolver.setPrefix("/WEB-INF/views/");

resolver.setSuffix(".jsp");

return resolver;

}

}

Let’s understand few important annotations as below:

The @Configuration is a class-level annotation indicating that an object is a source of bean definitions.

is a class-level annotation indicating that an object is a source of bean definitions. The @EnableWebMvc enables default Spring MVC configuration and provides the functionality equivalent to mvc:annotation-driven/ element in XML based configuration.

element in XML based configuration. The @ComponentScan scans the stereotype annotations (@Controller, @Service etc…) in a package specified by basePackages attribute.

InternalResourceViewResolver

This ViewResolver allows us to set properties such as prefix or suffix to the view name to generate the final view page URL:

@Bean

public InternalResourceViewResolver resolver() {

InternalResourceViewResolver resolver = new InternalResourceViewResolver();

resolver.setViewClass(JstlView.class);

resolver.setPrefix("/WEB-INF/views/");

resolver.setSuffix(".jsp");

return resolver;

}

We only need a simple JSP page, placed in the /WEB-INF/view folder. In this example, we have used helloworld.jsp as the view — /WEB-INF/views/helloworld.jsp

5. Servlet Container Initialization — SpringMvcDispatcherServletInitializer.java

Let’s configure Spring MVC DispatcherServlet and set up URL mappings to Spring MVC DispatcherServlet.

Create a SpringMvcDispatcherServletInitializer class by extending the AbstractAnnotationConfigDispatcherServletInitializer class as follows.

package net.javaguides.springmvc.helloworld.config; import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; /**

* @author Ramesh Fadatare

*/

public class SpringMvcDispatcherServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { @Override

protected Class <?> [] getRootConfigClasses() {

// TODO Auto-generated method stub

return null;

} @Override

protected Class <?> [] getServletConfigClasses() {

return new Class[] {

AppConfig.class

};

} @Override

protected String[] getServletMappings() {

return new String[] {

"/"

};

}

}

6. Model Class — HelloWorld.java

As we know that Spring MVC uses a model-view-controller design pattern. Let’s create a model — HelloWorld.java with message and DateTime fields. This model data will be rendered on a view (JSP file).

package net.javaguides.springmvc.helloworld.model; public class HelloWorld {

private String message;

private String dateTime;

public String getMessage() {

return message;

}

public void setMessage(String message) {

this.message = message;

}

public String getDateTime() {

return dateTime;

}

public void setDateTime(String dateTime) {

this.dateTime = dateTime;

}

}

Next, we will create Controller to handle a request, populate the model with some data and returns the view to a browser.

7. Controller Class — HelloWorldController.java

Create a HelloWorldController class annotated with @Controller annotation under net.javaguides.springmvc.helloworld.controller package and write the following code in it.

package net.javaguides.springmvc.helloworld.controller; import java.time.LocalDateTime; import org.springframework.stereotype.Controller;

import org.springframework.ui.Model;

import org.springframework.web.bind.annotation.RequestMapping; import net.javaguides.springmvc.helloworld.model.HelloWorld; /**

* @author Ramesh Fadatare

*/

@Controller

public class HelloWorldController { @RequestMapping("/helloworld")

public String handler(Model model) { HelloWorld helloWorld = new HelloWorld();

helloWorld.setMessage("Hello World Example Using Spring MVC 5!!!");

helloWorld.setDateTime(LocalDateTime.now().toString());

model.addAttribute("helloWorld", helloWorld);

return "helloworld";

}

}

8. View — helloworld.jsp

Let’s create an helloworld.jsp file under src/main/webapp/WEB-INF/views folder and write the following code in it.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"

pageEncoding="ISO-8859-1"%>

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

<!DOCTYPE html>

<html>

<head><%@ page isELIgnored="false" %>

<meta charset="ISO-8859-1">

<title>Spring 5 MVC - Hello World Example | javaguides.net</title>

</head>

<body>

<h2>${helloWorld.message}</h2>

<h4>Server date time is : ${helloWorld.dateTime}</h4>

</body>

</html>

9. Build + Deploy + Run an application

As we are using maven build tool so first, we will need to build this application using the following maven command:

clean install

Once build success, then we will run this application on tomcat server 8.5 in IDE or we can also deploy war file on external tomcat webapps folder and run the application.

10. Demo

Once an application is up and running in tomcat then hit this link into the browser: http://localhost:8080/springmvc5-helloworld-exmaple/helloworld

We will see the below page on the browser with the current date time and a message from a model.

That’s all. This is a very simple Spring MVC getting started example. You will learn more about Spring MVC on Spring MVC 5 Tutorial.

Note: If you face issues like ${helloWorld.message} Server date-time is : ${helloWorld.dateTime}. This is caused by the old JSP 1.2 descriptor and you can find a solution for this issue at ModelAndView’s model value is not displayed in JSP via EL. Try to use the latest JSP 2.0 descriptor will resolve this issue.

Related Spring MVC Tutorials and Articles