MVC

Spring 4 REST Hello World Example

In this example we shall show you how to create a simple application to make Rest calls, using the Spring Web MVC framework. Spring Web model-view-controller (MVC) is a Spring support framework for web-based presentation tiers. It provides a model-view-controller architecture and ready components that can be used to develop flexible and loosely coupled web applications.

On a previous Spring MVC HelloWorld example we explained how to build all nessecary components for an application with Spring MVC. Here, we will follow the same steps, this time including a rest call. We will create a Controller to implement the rest calls, 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 two methods, both handling GET requests from the Dispatcher. The first one is hello(ModelMap model). The org.springframework.ui.ModelMap is used as a generic model holder. Here we set to it an attribute called name, and a default value JCG Hello World!.

The second method is the displayMessage(@PathVariable String msg, ModelMap model) method. Here, the @PathVariable annotation is used on the msg argument of the method. Thus, the msg argument is binded to the value of the URI template variable of the method.

HelloWorldController.java

package com.javacodegeeks.snippets.enterprise;

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

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

		@RequestMapping(value = "/hello", method = RequestMethod.GET)
		public String hello(ModelMap model) {
			model.addAttribute("msg", "JCG Hello World!");
			return "helloWorld";
		}
		
		@RequestMapping(value = "/displayMessage/{msg}", method = RequestMethod.GET)
		public String displayMessage(@PathVariable String msg, ModelMap model) {
			model.addAttribute("msg", msg);
			return "helloWorld";
		}
		
	}

4. Create the View

The view is a simple jsp page, placed in /WEB-INF/ folder. It shows the value of the attribute that was set to the Controller.

helloWorld.jsp

<html>
<body>
	<h1>Spring 4.0.2 MVC web service</h1>
	
	<h3>Your Message : ${msg}</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 the application that a server needs to know. It is placed in the /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>

 
The mvc-dispatcher-servlet.xml file 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 also 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. Now we can start the server.

We’ll first call the first method, hitting on :

localhost:8080/springexample/helloWorld/hello

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

MVCResthello

The result is the default value that was passed to the ModelMap.

Next, let’s try calling the second method, passing also an argument, as shown below:

localhost:8080/springexample/helloWorld/displayMessage/Have a nice Day!

MVCRestMsg

As a result, the parameter passed through the Controller is displayed in the jsp page.

 
This was a Spring MVC Rest Hello World example.

Download the Eclipse project of this tutorial: SpringMVCRestExample

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.

3 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
aman
aman
7 years ago

Getting this error
type Exception report

message

description The server encountered an internal error () that prevented it from fulfilling this request.

exception

javax.servlet.ServletException: Servlet.init() for servlet mvc-dispatcher threw exception
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:117)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:174)
org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:881)
org.apache.coyote.http11.Http11BaseProtocol$Http11ConnectionHandler.processConnection(Http11BaseProtocol.java:674)
org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:541)
org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:81)
org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:689)
java.lang.Thread.run(Thread.java:745)
root cause

java.lang.NoSuchMethodError: javax.servlet.ServletContext.getContextPath()Ljava/lang/String;
org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:639)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:624)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:672)
org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:543)
org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:484)
org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
javax.servlet.GenericServlet.init(GenericServlet.java:212)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:117)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:174)
org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:881)
org.apache.coyote.http11.Http11BaseProtocol$Http11ConnectionHandler.processConnection(Http11BaseProtocol.java:674)
org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:541)
org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:81)
org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:689)
java.lang.Thread.run(Thread.java:745)
note The full stack trace of the root cause is available in the Apache Tomcat/5.5.36 logs.

Ishnk
Ishnk
7 years ago

The code doesnot works , it gives error I have spent two days recitfying the error still no use.

It is redirecting to the new URL : WEB-INF/helloWorld.jsp
and says 404 not found , where as it is availabe there itself.

paria
paria
5 years ago

very helpful .Thanks

Back to top button