Spring 3 MVC hello world example

In this tutorial, we show you a Spring 3 MVC hello world example, using Maven build tool.

Technologies used :

  1. Spring 3.2.13.RELEASE
  2. Maven 3
  3. JDK 1.6
  4. Eclipse 4.4
  5. Boostrap 3
Spring 4 MVC XML
Try this Spring 4 MVC hello world example.
Spring 3 MVC Annotation
Try this Spring 3 MVC hello world annotation example.

1. Project Structure

Download the project source code and review the project folder structure :

spring3-mvc-maven-project

2. Maven

A pom.xml template to quick start a Spring MVC project, it defines Spring 3 dependencies, an embedded Jetty container and Eclipse workspace configuration.

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.mkyong</groupId>
	<artifactId>spring3-web</artifactId>
	<packaging>war</packaging>
	<version>1.0-SNAPSHOT</version>
	<name>spring css</name>

	<properties>
		<jdk.version>1.6</jdk.version>
		<spring.version>3.2.13.RELEASE</spring.version>
		<jstl.version>1.2</jstl.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>${jstl.version}</version>
		</dependency>
	</dependencies>

	<build>
	  <plugins>
		<plugin>
			<groupId>org.apache.maven.plugins</groupId>
			<artifactId>maven-compiler-plugin</artifactId>
			<version>3.3</version>
			<configuration>
				<source>${jdk.version}</source>
				<target>${jdk.version}</target>
			</configuration>
		</plugin>

		<!-- embedded Jetty server, for testing -->
		<plugin>
			<groupId>org.eclipse.jetty</groupId>
			<artifactId>jetty-maven-plugin</artifactId>
			<version>9.2.11.v20150529</version>
			<configuration>
				<scanIntervalSeconds>10</scanIntervalSeconds>
				<webApp>
					<contextPath>/spring3</contextPath>
				</webApp>
			</configuration>
		</plugin>

		<!-- configure Eclipse workspace --> 
		<plugin>
			<groupId>org.apache.maven.plugins</groupId>
			<artifactId>maven-eclipse-plugin</artifactId>
			<version>2.9</version>
			<configuration>
				<downloadSources>true</downloadSources>
				<downloadJavadocs>true</downloadJavadocs>
				<wtpversion>2.0</wtpversion>
				<wtpContextName>spring3</wtpContextName>
			</configuration>
		</plugin>
	  </plugins>
	</build>

  </project>

3. Controller & Mapping

The @RequestMapping has been available since 2.5, but now enhanced to support REST style URLs.

HelloController.java

package com.mkyong.web.controller;

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;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class HelloController {

	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String printWelcome(ModelMap model) {

		model.addAttribute("message", "Spring 3 MVC Hello World");
		return "hello";

	}

	@RequestMapping(value = "/hello/{name:.+}", method = RequestMethod.GET)
	public ModelAndView hello(@PathVariable("name") String name) {

		ModelAndView model = new ModelAndView();
		model.setViewName("hello");
		model.addObject("msg", name);

		return model;

	}

}

4. JSP Views

A JSP page to display the value, and include bootstrap css and js.

html4strict

<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Maven + Spring MVC</title>
 
<spring:url value="/resources/core/css/hello.css" var="coreCss" />
<spring:url value="/resources/core/css/bootstrap.min.css" var="bootstrapCss" />
<link href="${bootstrapCss}" rel="stylesheet" />
<link href="${coreCss}" rel="stylesheet" />
</head>
 
<nav class="navbar navbar-inverse navbar-fixed-top">
  <div class="container">
	<div class="navbar-header">
		<a class="navbar-brand" href="#">Spring 3 MVC Project</a>
	</div>
  </div>
</nav>
 
<div class="jumbotron">
  <div class="container">
	<h1>${title}</h1>
	<p>
		<c:if test="${not empty name}">
			Hello ${name}
		</c:if>
 
		<c:if test="${empty name}">
			Welcome Welcome!
		</c:if>
    </p>
    <p>
	<a class="btn btn-primary btn-lg" href="#" role="button">Learn more</a>
    </p>
  </div>
</div>
 
<div class="container">
 
  <div class="row">
	<div class="col-md-4">
		<h2>Heading</h2>
		<p>ABC</p>
		<p>
		<a class="btn btn-default" href="#" role="button">View details</a>
		</p>
	</div>
	<div class="col-md-4">
		<h2>Heading</h2>
		<p>ABC</p>
		<p>
		<a class="btn btn-default" href="#" role="button">View details</a>
		</p>
	</div>
	<div class="col-md-4">
		<h2>Heading</h2>
		<p>ABC</p>
		<p>
		<a class="btn btn-default" href="#" role="button">View details</a>
		</p>
	</div>
  </div>
 
  <hr>
  <footer>
	<p>© Mkyong.com 2015</p>
  </footer>
</div>
 
<spring:url value="/resources/core/css/hello.js" var="coreJs" />
<spring:url value="/resources/core/css/bootstrap.min.js" var="bootstrapJs" />
 
<script src="${coreJs}"></script>
<script src="${bootstrapJs}"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
 
</body>
</html>

5. Spring XML Configuration

5.1 Enable component scanning, view resolver and resource mapping.

spring-web-servlet.xml

<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-3.2.xsd
        http://www.springframework.org/schema/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-3.2.xsd">

	<context:component-scan base-package="com.mkyong.web" />

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

	<mvc:resources mapping="/resources/**" location="/resources/" />
 
	<mvc:annotation-driven />
	
</beans>

5.2 Declares a DispatcherServlet in web.xml. If the Spring XML configuration file is NOT specified, Spring will look for the {servlet-name}-servlet.xml.

In this example, Spring will look for the spring-web-servlet.xml file.

web.xml

<web-app xmlns="http://java.sun.com/xml/ns/javaee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	version="2.5">
	
	<display-name>Spring3 MVC Application</display-name>

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

	<servlet-mapping>
		<servlet-name>spring-web</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>

</web-app>

You can define a Spring XML file via contextConfigLocation.

web.xml

	<servlet>
		<servlet-name>spring-web</servlet-name>
		<servlet-class>
                     org.springframework.web.servlet.DispatcherServlet
                </servlet-class>
		<load-on-startup>1</load-on-startup>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>/WEB-INF/spring-mvc-config.xml</param-value>
		</init-param>
	</servlet>

        <servlet-mapping>
		<servlet-name>spring-web</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>

6. Demo

The pom.xml file defines an embedded Jetty container. Issues mvn jetty:run to start the project.

Terminal

$ mvn jetty:run
...
[INFO] Started Jetty Server
[INFO] Starting scanner at interval of 10 seconds.

URL : http://localhost:8080/spring3

spring3-mvc-maven-xml-demo

URL : http://localhost:8080/spring3/hello/mkyong

spring3-mvc-maven-xml-demo2

7. WAR File

To create a WAR file for deployment :

Terminal

your-project$ mvn war:war

A WAR file will be created in project\target\ folder.


${Project}\target\spring3-web-1.0-SNAPSHOT.war

Download Source Code

Download it – spring3-mvc-maven-xml-hello-world.zip (51 KB)

References

  1. What new in Spring 3
  2. Spring 3 MVC and JSR303 @Valid example
  3. Spring 3 MVC and RSS feed example
  4. Spring 3 MVC and XML example
  5. Spring 3 MVC and JSON example

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

Leave a Reply

avatar
newest oldest most voted
Yunus
Guest
Yunus

hi thanks for every tutorial they are wonderful.

Anirudh
Guest
Anirudh

{name:.+} —> why is this :.+ for ?

Zoli
Guest
Zoli

Hello Plese help a little bit: in the MVC project example uri is include : http://www.springframework.org/tags
page. But it’s not wroking page. Please write me a working page. Many thanks!

Zoli
Guest
Zoli
April
Guest
April

There is a mistake in ‘hello.jsp’ file. The path to the resouece files ‘hello.js’ and ‘bootstrap.min.js’ should be under ‘js’ instead of ‘css’, and ‘jquery.min.js’ should be loaded before ‘bootstrap.min.js’. Otherwise it will generate 404 errors.

Ashi
Guest
Ashi

@RequestMapping(value = “/hello/{name:.+}”, method = RequestMethod.GET)
public ModelAndView hello(@PathVariable(“name”) String name) {

ModelAndView model = new ModelAndView();
model.setViewName(“hello”);
model.addObject(“msg”, name);

return model;

}

}

for this service it is giving me error 406 could you please help me on this?

HTTP Status [404] – [Not Found]

Type Status Report

Message /simplerestexample/WEB-INF/hello.jsp

Description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.

Ashi
Guest
Ashi

HTTP Status [406] – [Not Acceptable]

Type Status Report

Description The target resource does not have a current representation that would be acceptable to the user agent, according to the proactive negotiation header fields received in the request, and the server is unwilling to supply a default representation.

Apache Tomcat/8.5.15

Rajiv Rathinam
Guest
Rajiv Rathinam

Hi mkyong,

I downloaded the project spring-3-mvc-hello-world-example and tried running it using tomcat 7, I got resource not found error when the same I ran on jboss 7 and I got forbidden error. Can you help me with the solution, I’m curious to know how it works.

Yunus
Guest
Yunus

my application’s javascripts are not working.i can see whole page as you give above,however when i add dropdown list it can be seen, but it is not working.Even below, i fixed “core/css” part, as “core/js”

old code

new code

but it is not working

niche
Guest
niche

Download does not work. Extremely poor explanation for a new comer. Extreme waste of Time.

rrsg
Guest
rrsg

hi mkyong, Thanks for the helpful tutorial. Hi for some reason I donot see any logger statements on console…..also I tried to send logs to file and tht doesnt work too….It creates the file but no log statements… Plz help!!!!!!

mustafa
Guest
mustafa

there are “message” and “msg” in the controller as attribute, but in view there is not. instead “name” and “title” exist in view.

kammiti krishna
Guest
kammiti krishna

iam also having same doubt.

Anurag
Guest
Anurag

Hi,

css is loading but js resources are not getting loaded

GET http://localhost:8080/spring3/resources/core/css/hello.js
GET http://localhost:8080/spring3/resources/core/css/bootstrap.min.js 404 (Not Found)

above is the message in browser console

Younis Irshad
Guest
Younis Irshad

URL LINK IS: http://localhost:8080/spring3-mvc-maven-xml-hello-world/

ADD in Pom.xml:

javax.servlet
javax.servlet-api
3.1.0

Emrah
Guest
Emrah

How can i use static resources in spring with weblogic Server. web logic gives error when using

Sergio Muñoz
Guest
Sergio Muñoz

I tried to deploy the generated .war in Apache Tomcat 8.0.24, but I’m getting “HTTP Status 404”, should I change something? (I’m using the .zip source code)

alkumar
Guest
alkumar

Hello mkyong,
In below config according to the web-app_3_0.xsd, should be before .

spring-web

org.springframework.web.servlet.DispatcherServlet

1

contextConfigLocation
/WEB-INF/spring-mvc-config.xml

trackback
Spring 3 MVC hello world example – Annotation

[…] this tutorial, we will take the previous Maven + Spring MVC XML example, rewrite it to support @JavaConfig configuration, no more XML files, and deploy it into a Servlet […]

mkyong
Guest
mkyong

Try download it again.

Murtaza Abbas
Guest
Murtaza Abbas

spring-context-3.0.5.RELEASE.jar missing in pom.xml.

Deepesh Maheshwari
Guest
Deepesh Maheshwari

spring-webmvc
internally dependent on spring-web and spring-core , then why do you include them explicitly.

Please explain

mkyong
Guest
mkyong

Article is updated.

Lucas
Guest
Lucas

How to define which spring-webmvc to be use, because I wanted understand what is more important in the choice. thks

Thieus
Guest
Thieus

Hi mkyong,

I have a problem with the css file. i add in the “hello.jsp” this line:

i add css in the directory webapp/css/style.css
but css is not effective because of the following line in the file “web.xml”

mvc-dispatcher
/

Do you have a way to add css file?
Which directory have to add the css file?

mkyong
Guest
mkyong
Yas Ikeda
Guest
Yas Ikeda
Well, I just leave a note. “mvc-dispatcher-servlet.xml” does not need to be mentioned in in web.xml. contextConfigLocation However, we should not delete the whole part of this because application server will look for applicationContext.xml if web.xml doesn’t have this definition. “applicationContext.xml” seems the default value for the param contextConfigLocation. One more thing for “mvc-dispatcher-servlet.xml”. This file name is the default value for the spring mvc dispatcher servlet class. If you don’t like this name, you can change the name with the following configuration in . mvc-dispatcher org.springframework.web.servlet.DispatcherServlet contextConfigLocation /WEB-INF/spring-mvc.xml 1 Even in this case, you don’t need to have the… Read more »
mkyong
Guest
mkyong

Thanks for sharing, article is updated.

Ashi
Guest
Ashi

Hi Mkyong,

I have tried to run this code but it is giving me below error:-
HTTP Status [404] – [Not Found]

Type Status Report

Description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.

Apache Tomcat/8.5.15

Could you please help me in solving this issue?

cm reddy
Guest
cm reddy

Feb 25, 2015 5:40:32 PM org.springframework.web.servlet.DispatcherServlet noHandlerFound

WARNING: No mapping found for HTTP request with URI [/SpringMVC/welcome] in DispatcherServlet with name ‘mvc-dispatcher’

I DIDN’T CHANGE ANY THING IN THE ABOVE CODE….STILL I AM GETTING THIS EXCEPTION.

hari
Guest
hari

I tried to follow your tutorial step by step but I get the following error
IOException parsing XML document from ServletContext resource [/WEB-INF/applicationContext.xml]; nested exception is java.io.FileNotFoundException

my web.xml is the same as yours not sure why it is looking for applicationContext.xml instead of mvc-dispatcher-servlet.xml

Yas Ikeda
Guest
Yas Ikeda

Hi hari,
I just thought my findings seem to possibly help you. See my latest post. (> 6)

Vivek
Guest
Vivek

Hi All,

As I can see most of the people getting the same error which is just because you people are bit confused in the Directory Structure.Understand the code and set the path accordingly in the xml file

Ricardo
Guest
Ricardo

Amazing quick start tutorial, as always. Thank you.

Mangesh
Guest
Mangesh

For downloaded example

Open the project’s properties (e.g., right-click on the project’s name in the project explorer and select “Properties”).
Select “Deployment Assembly”.
Click the “Add…” button on the right margin.
Select “Java Build Path Entries” from the menu of Directive Type and click “Next”.
Select all “Maven Dependencies” from the Java Build Path Entries menu and click “Finish”.
You should see “Maven Dependencies” added to the Web Deployment Assembly definition.

ttwon24
Guest
ttwon24

Hi mKyong.
i have 2 folder(WEB-INF/views/login and WEB-INF/views/news). in web.xml and mvc-dispatcher-servlet.xml, i do not config it, could you help me!!!!!

Ismael
Guest
Ismael

Hi MKyong,
Can you make a tutorial using JSF please?

Varun Krishna
Guest
Varun Krishna

Hi all
How do I start this project in Spring Tool Suite (STS) ?