HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / Spring MVC / Spring MVC Hello World Example with Maven and JSTL

Spring MVC Hello World Example with Maven and JSTL

In this Spring MVC tutorial, we are building hello world application using Spring MVC framework. Follow the given instructions step by step and learn the basics. We have used JSTL for writing the view files.

1. Development environment

  1. Maven
  2. Eclipse juno
  3. Tomcat 7

2. Create Spring MVC Application

2.1. Create maven web application

To create a maven web application, open command prompt and make current working directory into eclipse workspace.

Now execute below command.

$ mvn archetype:generate -DgroupId=com.howtodoinjava.mvc 
							-DartifactId=firstSpringApplication
							-DarchetypeartifactId=maven-archetype-webapp 
							-DinteractiveMode=false

Please remove the line break from above command. I added it for making it readable.

Now run below given commands. This will convert the created project into eclipse web project.

$ cd firstSpringApplication

$ mvn eclipse:eclipse -Dwtpversion=2.0

2.2. Update maven dependencies

Update the pom.xml file with these dependencies.

<properties>
    <spring.version>3.0.5.RELEASE</spring.version>
</properties>

<!-- Spring 3 dependencies -->
<dependency>
	<groupid>org.springframework</groupid>
	<artifactId>spring-core</artifactId>
	<version>${spring.version}</version>
	<scope>runtime</scope>
</dependency>

<dependency>
	<groupid>org.springframework</groupid>
	<artifactId>spring-web</artifactId>
	<version>${spring.version}</version>
	<scope>runtime</scope>
</dependency>

<dependency>
	<groupid>org.springframework</groupid>
	<artifactId>spring-webmvc</artifactId>
	<version>${spring.version}</version>
	<scope>runtime</scope>
</dependency>

<dependency>
	<groupid>javax.servlet</groupid>
	<artifactId>jstl</artifactId>
	<version>1.2</version>
	<scope>runtime</scope>
</dependency>

<dependency>
	<groupid>taglibs</groupid>
	<artifactId>standard</artifactId>
	<version>1.1.2</version>
	<scope>runtime</scope>
</dependency>

3. Create Dispatcher Servlet

3.1. Update web.xml

Update web.xml for Servlet mapping and spring configuration location.

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>
  <display-name>www.howtodoinjava.com</display-name>
  
  <servlet>
		<servlet-name>spring-mvc</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>
 
	<servlet-mapping>
		<servlet-name>spring-mvc</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
 
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>/WEB-INF/spring-mvc-servlet.xml</param-value>
	</context-param>
 
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
</web-app>

3.2. Bean configuration file

We will need to write configuration file (spring-mvc-servlet.xml) inside WEB-INF folder. We can name it at our will, but keep remember that it must match the servlet name we declared in web.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"
	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">

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

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

</beans>

3. Create Spring MVC Controller

This request handler will receive all requests to a particular URL and return the model data to view handler configured.

package com.howtodoinjava.web;

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("/access")
public class DemoController
{
	@RequestMapping(method = RequestMethod.GET)
	public String printWelcome(ModelMap model)
	{
		model.addAttribute("message", "Spring 3 MVC Hello World !! Thanks to www.howtodoinjava.com");
		return "helloWorld";
	}
}

4. Create Views

Our view is a jsp file, which will be rendered in browser when related view will be returned from server.

<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<%@ taglib prefix="x" uri="http://java.sun.com/jstl/xml" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jstl/fmt" %>
<%@ taglib prefix="sql" uri="http://java.sun.com/jstl/sql" %>

<html>
	<head>
		<title>My first example using Spring 3 MVC</title>
	</head>
	<body>
		<h1>Welcome message : <c:out value="${message}"></c:out></h1>
	</body>
</html>

5. Demo

To run the application, configure tomcat server in eclipse. Now, right click on project and choose run as. On sub menu, choose Run on server.

Now type on browser: http://localhost:8080/firstSpringApplication/access

We should be able to see the message “Spring 3 MVC Hello World !! Thanks to www.howtodoinjava.com” in browser.

If you find any problem in running or deploying given application, drop me a comment.

Download source code

Happy Learning !!

Was this post helpful?

Let us know if you liked the post. Thatโ€™s the only way we can improve.
TwitterFacebookLinkedInRedditPocket

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Feedback, Discussion and Comments

  1. Jonel

    September 10, 2014

    Im a beginner it is a great Tutorial it really helps me to build or create a simple spring mvc 3 apps. sir can I ask a favor can you create a tutorial of spring mvc 3 w/out using maven. I mean by using jar files only ..

    sorry theres something wrong on my grammar im not that good in english

    ~ NewbieJonel

    • Lokesh Gupta

      September 10, 2014

      You can find all required jar files here: https://howtodoinjava.com/spring-orm/spring3-hibernate4-integration-example/

  2. Ravikanth

    September 9, 2014

    You have mentioned RequestMapping at class level for access – @RequestMapping(“/access”)
    And mentioned RequestMapping method as RequestMethod.GET for method printWelcome – @RequestMapping(method = RequestMethod.GET)
    I have couple of questions related to this, when we dont have any RequestMapping value at method level. – Only at class level like access – @RequestMapping(“/access”)
    1) Can we have multiple methods with same RequestMethod – such as RequestMethod.GET for printWelcome, printWelcomeNew ..
    If yes, How will application directs to proper method ?
    2) If we have multiple methods with DIFFERENT RequestMethod – such as RequestMethod.GET for printWelcome, RequestMethod.POST for printWelcomePost, RequestMethod.PUT for printWelcomePut..
    How will application directs to proper method – how GET, POST, PUT plays role here, and how it manages to go to proper method ?
    When it will go to Post method, and Put method ?

    • Lokesh Gupta

      September 10, 2014

      Very good question. And the answer lies in use of annotations.

      RESTEasy uses a regex based system for paths and selects the most closely matching pattern. In the event of a collision the last one matched is used.
      Further for matching methods, resteasy uses build path expressions as above link, then it matches method type (POST, GET annotations etc.) and it also matches the media types as well. When all above are matched (if mentioned in method declaration) then only method is invoked.

      The name of the method does not play any role here. You can name your method absolutely anything i.e. abc, xyz etc. No effect at all.

  3. Chandra Sekhar

    August 27, 2014

    Suggestion : In the above command while creating the firstSpringApplication it is typed as -DarchetypeartifactId. If we run the above command as it is, it is creating Java application. It should be corrected as -DarchetypeArtifactId to create firstSpringApplication as web application

  4. shashi

    August 5, 2014

    hey, nice tutorial.. ๐Ÿ™‚
    just wanted to ask your opinion on how much difference is there between Jersey API and Spring MVC for REST webservices development. which one is preferable and in what circumstances?

    • shashi

      August 5, 2014

      actully i was reading your post on REST webservice, and i was redirected here. Mistakenly posted the comment on this post instead of posting there ๐Ÿ˜›

      • Lokesh Gupta

        August 5, 2014

        Shashi, it’s very broad question and requires a lot of analysis and I believe that at last there is not much difference when it comes to implement code. Real decision lies in scope of application. If you are building an “webservices” of enterprise level that does not need MVC [UI interaction] then you should go for JAX-RS, RESTeasy or Jersey. All are equally powerful.
        If application is mainly MVC and you need to plugin some REST APIs additionally, Spring MVC is for that purpose only. Remember that Jersey/RESTeasy are mainly intended for building webservices only.

  5. deepak

    May 21, 2014

    it is showing HTTP Status 404 – in tomcat

    • Lokesh Gupta

      May 21, 2014

      Check server logs in console what’s going on wrong during startup.

  6. deepak

    May 21, 2014

    An internal error occurred during: “Updating status for Tomcat v7.0 Server at localhost…”.
    java.lang.IndexOutOfBoundsException

    • Lokesh Gupta

      May 21, 2014

      Please provide the complete stacktrace..

  7. Gus

    November 28, 2013

    How does the url “../firstSpringApplication/access” know which jsp to display ? Where is this link/mapping?

    • Lokesh Gupta

      November 28, 2013

      Please look at InternalResourceViewResolver mapping.

  8. avinash

    July 30, 2013

    working finee

  9. Rajendra Joshi

    December 21, 2012

    choose a number or apply filter (format :[groupId],artifactId ,case sensitive contains):236:

    so what should I enter? and what is the meaning of these parameters?

    and how to add jdocklet.jar

  10. Rajendra Joshi

    December 20, 2012

    at command prompt asking me to enter –
    choose a number or apply filter (format :[groupId],artifactId ,case sensitive contains):236:

    so what should I enter? and what is the meaning of these parameters?

Comments are closed on this article!

Search Tutorials

Spring MVC Tutorial

  • MVC – Introduction
  • MVC – Hello World
  • MVC – JSTL
  • MVC – @RequestMapping
  • MVC – Custom Validator
  • MVC – JSR-303 Validation
  • MVC – Dropdown
  • MVC – Submit Form
  • MVC – MessageSourceAware
  • MVC – XmlViewResolver
  • MVC – i18n and i10n
  • MVC – Interceptor
  • MVC – HandlerInterceptor
  • MVC – Multi File Upload (Ajax)
  • MVC – Multi File Upload
  • MVC – File Download
  • MVC – Interview Questions
  • InternalResourceViewResolver
  • ResourceBundleViewResolver
  • SimpleMappingExceptionResolver
  • annotation-config vs component-scan
  • ContextLoaderListener vs DispatcherServlet

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Sealed Classes and Interfaces