Creating Hello World Application using Spring MVC on Eclipse IDE

In this tutorial we will go into some detail on how to set up your Eclipse IDE environment so that you can develop Spring MVC projects. In this post, we will create our first Spring MVC project with the all to familiar “Hello World” sample program. However, it will teach you some valuable concepts and provide some insight into setting up your MVC project.

Getting Started

In order to run this tutorial yourself, you will need the following:

Required JAR Files

  • commons-logging-1.2.jar
  • jstl-1.2.jar
  • org.springframework.asm-3.0.1.RELEASE-A.jar
  • org.springframework.beans-3.0.1.RELEASE-A.jar
  • org.springframework.context-3.0.1.RELEASE-A.jar
  • org.springframework.core-3.0.1.RELEASE-A.jar
  • org.springframework.expression-3.0.1.RELEASE-A.jar
  • org.springframework.web-3.0.1.RELEASE-A.jar
  • org.springframework.web.servlet-3.0.1.RELEASE-A.jar

Create Dynamic Web Project in Eclipse

Now that you have downloaded all dependencies, we can go ahead and create our Dynamic Web Project in Eclipse.

Open Eclipse and click on File -> New -> Dynamic Web Project or use the shortcut Alt + Shift + N.

Once you get the New Dynamic Web Project Dialog, choose the project name, in my case I chose SpringMVCExamples but you can use any name you prefer. Make sure you select the appropriate Target Runtime. In my case, I chose “Apache Tomcat version 7.0”.

spring mvc dynamic web project

Once you create the Dynamic Web Project, your Eclipse Project Explorer will look like:

spring mvc project

Copy JAR Files

You will need to copy all dependency libraries to the WebContent -> WEB-INF -> lib folder. Your folder should look like:

spring mvc libs

Configure DispatcherServlet (web.xml)

Spring MVC framework is built around a main servlet DispatcherServlet, also called Front Controller, that handles request from clients and dispatches to back end components like handler mapping, controller, view resolver and views and sends responses back to clients. This servlet must be defined in the deployment descriptor (web.xml). You will notice that there are servlet tags to define the dispatcher servlet. In this example, the dispatcher servlet will be mapped to any pattern from the root of the directory onwards.

<?xml version="1.0" encoding="UTF-8"?>
  <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
     xmlns="http://java.sun.com/xml/ns/javaee" 
     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" 
     id="WebApp_ID" version="3.0">
  
  <display-name>SpringMVCExamples</display-name>
  
  <servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
     <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
  
</web-app>

Configure Spring Web DispatcherServlet (dispatcher-servlet.xml)

The name of the file will be based on the web.xml entry for servlet-mapping, so in my case since I called the servlet-name dispatcher, the config file will be called dispatcher-servlet.xml.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:context="http://www.springframework.org/schema/context"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:mvc="http://www.springframework.org/schema/mvc"
 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd  http://www.springframework.org/schema/context  http://www.springframework.org/schema/context/spring-context.xsd  http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd" >

 <context:component-scan base-package="com.avaldes.controller" />

  <bean id="viewResolver" 
    class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
      <property name="prefix">
        <value>/WEB-INF/</value>
      </property>
    
      <property name="suffix">
        <value>.jsp</value>
      </property>
  </bean>

</beans>

The Spring Controller

As mentioned in previous tutorial, the DispatcherServlet will take client requests and consult the appropriate handlermapping and then dispatches the request to the appropriate controllers to handle the request. The following class shows you a typical setup for a controller. You will notice, that we have added two annotations already defined in the HelloController class. The @Controller annotation indicates that this particular class is playing the role of a controller. The @RequestMapping annotation tells Spring that the this method will process requests beginning with /hello in the URL path. You will also notice, that I have added method=RequestMethod.GET parameter. This parameter states that it will only handle requests using HTTP GET. The default is GET, so I could have left this out and the end result would have been the same. The method parameter can also accept method=RequestMethod.POST method but I will be explaining that in a subsequent tutorial.

In our controller method helloWorld(), you will notice that we have added an Object called message, with the String of “Hello World from Spring MVC 3.0 !!!”. The method returns a ModelAndView object which gets resolved to a view called HelloWorld.jsp and the model is returned as well to be used when rendering the view by the JSP using the embedded JSTL tag(s).

Controller Class (HelloController.java)

package com.avaldes.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class HelloController {

  @RequestMapping(value="/hello", method=RequestMethod.GET)
  public ModelAndView helloWorld() {
    ModelAndView model = new ModelAndView("HelloWorld");
    model.addObject("message", "Hello World from Spring MVC 3.0 !!!");

    return model;
  }    
}

Spring JSP Views

Spring MVC supports many types of views for the presentation layer. These include many template based technologies including JSPs, Velocity, FreeMarker, or ThymeLeaf. However, the most commonly used technology for Spring MVC View is JSP templates embedded with JSTL.

View file (HelloWorld.jsp)

<html>
<head>
  <title>Spring MVC Examples</title>
</head>
<body>
    <h1>Creating Hello World Application using Spring MVC on Eclipse IDE</h1>
    
    <h2>${message}</h2>
</body>
</html>

Complete Project Overview

I have added the project overview to give you a full view of the structure and show you all files contained in this sample project.

spring mvc eclipse project

Hello World Output

spring mvc hello world

Download the Code

That’s It!

I hope you enjoyed this tutorial. It was certainly a lot of fun putting it together and testing it out. Please continue to share the love and like us so that we can continue bringing you quality tutorials. Happy Coding!!!

spring helloworld

Related Spring Posts

  • Creating Hello World Application using Spring MVC on Eclipse IDE
    In this tutorial we will go into some detail on how to set up your Eclipse IDE environment so that you can develop Spring MVC projects. In this post, we will create our first Spring MVC project with the all to familiar “Hello World” sample program.
  • Spring MVC Form Handling Example
    The following tutorial will guide you on writing a simple web based application which makes use of forms using Spring Web MVC framework. With this web application you will be able to interact with the customer entry form and enter all of the required values and submit them to the backend processes. I have taken the liberty of using CSS to beautify and transform the HTML page from a standard drab look and feel to a more appealing view.
  • Spring @RequestHeader Annotation Example
    In this tutorial, we will discuss the different ways that Spring MVC allow us to access HTTP headers using annotation. We will discuss how to access individual header fields from the request object as well accessing all the headers by supplying Map and then iterating through the LinkedHashMap collection. We will also show you how to set the headers in the response object.
  • Spring MVC Exception Handling using @ExceptionHandler with AngularJS GUI
    Good exception handling is a essential part of any well developed Application Framework and Spring MVC is no exception — pardon the pun. Spring MVC provides several different ways to handle exceptions in our applications. In this tutorial, we will cover Controller Based Exception Handling using the @ExceptionHandler annotation above the method that will handle it.
  • Spring RESTful Web Service Example with JSON and Jackson using Spring Tool Suite
    For this example, I will be using Spring Tool Suite (STS) as it is the best integrated development environment for building the Spring framework projects. Spring is today's leading framework for building Java, Enterprise Edition (Java EE) applications. One additional feature that makes Spring MVC so appealing is that it now also supports REST (REpresentational State Transfer) for build Web Services.
  • Spring MVC RESTful Web Service Example with Spring Data for MongoDB and ExtJS GUI
    This post will show another example of how to build a RESTful web service using Spring MVC 4.0.6, Spring Data for MongoDB 1.6.1 so that we can integrate the web application with a highly efficient datastore (MongoDB 2.6). In this tutorial we will walk you through building the web service and NoSQL database backend and show you how to implement CRUD (Create, Read, Update and Delete) operations.
  • Building DHTMLX Grid Panel User Interface with Spring MVC Rest and MongoDB Backend
    In this tutorial we will show how easy it is to use DHTMLX dhtmlxGrid component while loading JSON data with Ajax pulling in data from the Spring MVC REST web service from our MongoDB data source. You will see how simple it is to create a visually appealing experience for your client(s) with minimal javascript coding.
  • Spring MVC with JNDI Datasource for DB2 on AS/400 using Tomcat
    In this tutorial we will discuss how to set up Spring MVC web services and configure a JNDI Datasource using Tomcat and connect to IBM DB2 Database on a AS/400. JNDI (Java Naming and Directory Interface) provides and interface to multiple naming and directory services.
  • Java Spring MVC Email Example using Apache Velocity
    In this tutorial we will discuss how to set up a Java Spring MVC RESTful Webservice with Email using Apache Velocity to create a Velocity template that is used to create an HTML email message and embed an image, as shown below, using MIME Multipart Message.
  • Implementing Basic and Advanced Search using Angular Material Design, Grid-UI, Spring MVC REST API and MongoDB Example
    In this tutorial we will discuss how to implement basic and advanced search techniques in MongoDB using AngularJS and Google’s Material Design with Spring MVC REST API backend. The advanced search user interface (UI) will use logical operators and build a JSON object which contains the search field name, boolean or logical operator and the search value.
  • Spring MVC Interceptor using HandlerInterceptorAdapter Example
    In this tutorial we will discuss how to use the HandlerInterceptorAdapter abstract class to create a Spring MVC interceptor. These interceptors are used to apply some type of processing to the requests either before, after or after the complete request has finished executing.

Please Share Us on Social Media

Facebooktwittergoogle_plusredditpinterestlinkedinmail

Leave a Reply

Your email address will not be published. Required fields are marked *