MVC

Spring MVC Hello World Example

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 Model, that encapsulates the application data
  • The View, which is responsible for rendering the model data and in general it generates HTML output that the client’s browser can interpret.
  • The Controller, which processes user requests and builds appropriate model and passes it to the view for rendering.

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:

  • The DispatcherServlet receives a request.
  • The DispatcherServlet uses the HandlerMapping so as to call the appropriate Controller.
  • The Controller takes the request and calls the appropriate service methods based on used GET or POST method. The service method will set model data based on defined business logic and returns view name to the DispatcherServlet.
  • The DispatcherServlet will take help from ViewResolver to pickup the defined view for the request.
  • The DispatcherServlet passes the model data to the view which is finally rendered on the browser.

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:

  • /src/main/java folder, that contains source files for the dynamic content of the application,
  • /src/test/java folder contains all source files for unit tests,
  • /src/main/resources folder contains configurations files,
  • /target folder contains the compiled and packaged deliverables,
  • /src/main/resources/webapp/WEB-INF folder contains the deployment descriptors for the Web application ,
  • the pom.xml is the project object model (POM) file. The single file that contains all project related configuration.

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

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.javacodegeeks.snippets.enterprise</groupId>
  <artifactId>springexample</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>springexample Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    
    <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>
  </dependencies>
  <build>
    <finalName>springexample</finalName>
  </build>
  
	<properties>
		<spring.version>4.0.2.RELEASE</spring.version>
	</properties>
</project>

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

<html>
<body>
	<h1>Spring 4.0.2 MVC web service</h1>
	
	<h3>Name : ${name}</h3>	
</body>
</html>

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

<?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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 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>Archetype Created Web Application</display-name>
 
	<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> 
</web-app>

 
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

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

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

</beans>

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:

tomcatresult
 
This was a Spring MVC Hello World example.
Download the Eclipse project of this tutorial:SpringMVCHelloWorldExample

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.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button