Spring MVC Hello World Example (original) (raw)

This is an example of the Spring MVC framework. The Spring Web model-view-controller (MVC) is a Spring support framework for web-based presentation tiers. Before creating a simple Hello World example in Spring MVC we shall check on the Spring MVC architecture.

The Spring web model-view-controller (MVC) framework provides a model-view-controller architecture and ready components that can be used to develop flexible and loosely coupled web applications.

Spring MCV basically consists of:

The framework is designed around a DispatcherServlet that handles all the HTTP requests and responses. Basically, the sequence of events corresponding to an incoming HTTP request to DispatcherServlet is performed by the following steps:

All the above mentioned components (HandlerMapping, Controller and ViewResolver) are parts of the WebApplicationContext which is an extension of the plain ApplicationContext with some extra features necessary for web applications.

Now, we can move on to create a simple example. We will create a Controller, a view (jsp) and we will add the necessary configuration files, and then we will use an application server to run the example.

Our preferred development environment is Eclipse. We are using Eclipse Juno (4.2) version, along with Maven Integration plugin version 3.1.0. You can download Eclipse from here and Maven Plugin for Eclipse from here. The installation of Maven plugin for Eclipse is out of the scope of this tutorial and will not be discussed. We are also using JDK 7_u_21. Tomcat 7 is the application server used.

Let’s begin,

1. Create a new Maven project

Go to File -> Project ->Maven -> Maven Project.

New-Maven-Project

In the “Select project name and location” page of the wizard, make sure that “Create a simple project (skip archetype selection)” option is unchecked, hit “Next” to continue with default values.

new project

Here the maven archetype for creating a web application must be added. Click on “Add Archetype” and add the archetype. Set the “Archetype Group Id” variable to "org.apache.maven.archetypes", the “Archetype artifact Id” variable to "maven-archetype-webapp" and the “Archetype Version” to "1.0". Click on “OK” to continue.

maven-archetype-webapp

In the “Enter an artifact id” page of the wizard, you can define the name and main package of your project. Set the “Group Id” variable to "com.javacodegeeks.snippets.enterprise" and the “Artifact Id” variable to "springexample". The aforementioned selections compose the main project package as "com.javacodegeeks.snippets.enterprise.springexample" and the project name as "springexample". Set the “Package” variable to "war", so that a war file will be created to be deployed to tomcat server. Hit “Finish” to exit the wizard and to create your project.

springmvcnewproject

The Maven project structure is shown below:

springmvc

It consists of the following folders:

2. Add Spring-MVC dependencies

Add the dependencies in Maven’s pom.xml file, by editing it at the “Pom.xml” page of the POM editor. The dependency needed for MVC is the spring-webmvc package, as shown below:

pom.xml

4.0.0 com.javacodegeeks.snippets.enterprise springexample war 0.0.1-SNAPSHOT springexample Maven Webapp http://maven.apache.org junit junit 3.8.1 test

<dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>${spring.version}</version>
    </dependency>
springexample
<properties>
    <spring.version>4.0.2.RELEASE</spring.version>
</properties>

3. Create the Controller

The Controller is where the DispatcherServlet will delegate requests. The @Controller annotation indicates that the class serves the role of a Controller. The @RequestMapping annotation is used to map a URL to either an entire class or a particular handler method. Here, it is used for both cases. The HelloWorldController.java class consists of a method, hello(ModelMap model) that will handle a GET request from the Dispatcher. The org.springframework.ui.ModelMap is used as a generic model holder. Here we set to it an attribute called name, and the value JCG Hello World!.
HelloWorldController.java

package com.javacodegeeks.snippets.enterprise;

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

@Controller @RequestMapping("/helloWorld") public class HelloWorldController {

    @RequestMapping(method = RequestMethod.GET)
    public String hello(ModelMap model) {

        model.addAttribute("name", "JCG Hello World!");
        return "helloWorld";

    }
    
}

4. Create the View

Spring MVC supports many types of views for different presentation technologies, such as JSPs, HTML, PDF, Excel worksheets, XML etc. The view part of this MVC example is a simple jsp page, that shows the value of the attribute that was set to the Controller. It must be placed in /WEB-INF/ folder.
helloWorld.jsp

Spring 4.0.2 MVC web service

<h3>Name : ${name}</h3>	

5. Configure the application

The files that we must configure in the application are the web.xml file and the mvc-dispatcher-servlet.xml file.

The web.xml file is the file that defines everything about your application that a server needs to know. It is placed in /WEB-INF/ directory of the application. The <servlet> element declares the DispatcherServlet. When the DispatcherServlet is initialized, the framework will try to load the application context from a file named [servlet-name]-servlet.xml located in /WEB-INF/ directory. So, we have created the mvc-dispatcher-servlet.xml file, that will be explained below. The <servlet-mapping> element of web.xml file specifies what URLs will be handled by the DispatcherServlet.

web.xml

Archetype Created Web Application

<servlet>
    <servlet-name>mvc-dispatcher</servlet-name>
    <servlet-class>
        org.springframework.web.servlet.DispatcherServlet
    </servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>mvc-dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping> 

Now, let’s check on the mvc-dispatcher-servlet.xml file. It is also placed in WebContent/WEB-INF directory. It uses the <context:component-scan> so that the Spring container will search for all annotated classes under the com.javacodegeeks.snippets.enterprise package.
The org.springframework.web.servlet.view.InternalResourceViewResolver is defined as a bean, and is used as internal resource views resolver, meaning that it will find the jsp and html files in the WebContent/WEB-INF/ folder. We can set properties such as prefix or suffix to the view name to generate the final view page URL, as shown below:
mvc-dispatcher-servlet.xml

<context:component-scan base-package="com.javacodegeeks.snippets.enterprise" />

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

6. Run the application

In order to run the application we first build the project with Maven. All we have to do is right click on the project and select -> Run As: Maven build. The goal must be set to package. The war file produced must be placed in webapps folder of tomcat.

After starting tomcat, we can hit on :

localhost:8080/springexample/helloWorld

on a browser, and the result is the one shown below:

Photo of Theodora Fragkouli

Theodora has graduated from Computer Engineering and Informatics Department in the University of Patras. She also holds a Master degree in Economics from the National and Technical University of Athens. During her studies she has been involved with a large number of projects ranging from programming and software engineering to telecommunications, hardware design and analysis. She works as a junior Software Engineer in the telecommunications sector where she is mainly involved with projects based on Java and Big Data technologies.