Spring MVC 5 - Hello World Example




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

    Spring MVC Tutorials and Articles

Video

This tutorial explained in below youtube video. Subscribe to our youtube channel for future video updates.

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

Spring MVC Hello World Application Flow

Development Steps

  1. Create Maven Web Application
  2. Add Dependencies - pom.xml File
  3. Project Structure
  4. Spring Configuration - AppConfig.java
  5. Servlet Container Initialization - MySpringMvcDispatcherServletInitializer.java
  6. Model Class - HelloWorld.java
  7. Controller Class - HelloWorldController.java
  8. View - helloworld.jsp
  9. Build + Deploy + Run an application
  10. Demo

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 maven web application, refer below pom.xml file jar dependencies.

2. Add Dependencies - pom.xml File

Refer the following pom.xml file and add jar dependencies to your pom.xml.
<project xmlns="https://maven.apache.org/POM/4.0.0"
 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>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.1.0.RELEASE</version>
        </dependency>

        <!-- 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 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.
  • The @EnableWebMvc enables default Spring MVC configuration and provides the functionality equivalent to mvc:annotation-driven/ 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 browser: http://localhost:8080/springmvc5-helloworld-exmaple/helloworld
We will see below page on the browser with current date time and a message from a model.

That's all. This is 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.

Comments

  1. the page shows:
    ${helloWorld.message}
    Server date time is : ${helloWorld.dateTime}

    ReplyDelete
    Replies
    1. Can you check all JSTL jar files and configuration added?. Clone source code of this tutorial from my GitHub repository Spring MVC Tutorial - GitHub Repository

      Delete
    2. I get the same error, and I really don't want to clone your repository so how can we check where the jstl jar files and configurations are added

      Delete
    3. Check in my article, pom.xml has two JSTL Dependency and <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> code in JSP file. This should work.

      Delete
    4. Hello Ramesh,
      This seems like a good article. But I am facing exact same issue. Both jstl-api and jstl dependencies exists in the pom file and in .jsp file mentioned uri exists, but I am also getting $ related issue. not being processed

      Delete
    5. Found the issue.
      Take a look at Mkyong's page
      https://www.mkyong.com/spring-mvc/modelandviews-model-value-is-not-displayed-in-jsp-via-el/

      Delete
    6. Correct. I haven't used old JSP 1.2 descriptor so it worked for me. If you are using old JSP 1.2 descriptor then this link will solve your issue - https://www.mkyong.com/spring-mvc/modelandviews-model-value-is-not-displayed-in-jsp-via-el/

      Delete
    7. Add <%@ page isELIgnored="false" %> line within a head of helloworld.jsp file should resolve your issue. I added this line so try now and let me know if you face any issues.

      Delete
  2. hi I have a 404 resource not available error and this tomcat message: "org.springframework.web.servlet.DispatcherServlet.noHandlerFound No mapping for GET"
    Any idea why?
    thanks

    ReplyDelete
  3. Hello Ramesh,
    In the above tutorial we have defined our JSp file inside WEB-INF folder, How could we directly hit the page from url? Definitely getting the 404

    ReplyDelete
    Replies
    1. There is view mapping defined in InternalResourceViewResolver bean. Hit http://localhost:8080/springmvc5-helloworld-exmaple/helloworld link in browser should work.

      Delete
  4. Hi again, If we put the helloWorld.jsp data inside the index.jsp our model is not getting the data on the front page, the controller is not being hit at all. could you please help.

    ReplyDelete
  5. Thank u very much. It worked perfectly

    ReplyDelete

Post a Comment