Spring MVC Tutorial

Filed Under: Spring

In this Spring MVC Tutorial, we will learn how to develop Spring MVC web application using Spring Tool Suite. Spring MVC framework is widely used for java web applications.

Spring MVC

spring mvc, spring mvc tutorial
Just like Struts Framework, Spring MVC is also based on Java EE Servlet and JSP technologies and implement ModelViewController design pattern.

Spring MVC Tutorial

We have earlier seen how Spring Dependency Injection works and in this tutorial we will learn how to create a simple web application using Spring MVC framework.

We can use Eclipse or IntelliJ IDE for the Spring projects development, but SpringSource provides Spring Tool Suite (STS) that is an IDE based on Eclipse and comes with in-built VMware vFabric tc Server that is built on top of Apache Tomcat container and optimised for Spring-based applications.

I would use STS for Spring MVC tutorial and other future tutorials because it makes a developer life easier by providing the following features:

  • Support for creating skeletal Spring applications (MVC, Rest, Batch etc), good for starting the project from scratch. We will soon see in this spring MVC tutorial how easy it is to create a Spring MVC project.
  • Provides useful features such as creating Spring Configuration files, parsing config files and classes to provide useful information about them.
  • Automatic validation of Spring application
  • Refactoring support to easily make project changes, the changes get reflected in config files too.
  • Code assist for not only classes but configuration files too, I like this feature a lot because most of the times we need to know what we can use and its details.
  • Best support for Aspect Oriented Programming (AOP) through the integration of AspectJ.

Looking at all the features STS provide, I was sold for this and decided to use it for Spring application and till now I am very happy with it.

Just Download the STS from STS Official Download Page and install it. I am using STS 3.4.0.RELEASE that is based on Eclipse 4.3.1 release.

Spring Tool Suite, Spring MVC, Spring MVC Tutorial for beginners

If you don’t want to use STS and want to get its facilities in existing Eclipse, then you need to install its plugin from Eclipse Marketplace. Use below image as a reference and make sure to chose the correct STS version for installation. Below plugin is good for Eclipse Kepler.

Spring Tool Suite, Spring MVC, Spring MVC Tutorial Eclipse

If you don’t want to use SpringSource server, you can deploy the application in any other Java EE container such as Tomcat, JBoss etc. For this tutorial, I will use the server that ships with STS but I have tested the application by exporting it as WAR file into separate tomcat server and it’s working fine.

Now that our server environment and IDE is ready, let’s proceed to create our first Spring MVC project. Below steps are valid for STS as well as Eclipse with STS plugins.

Creating Spring MVC Application in STS or Eclipse

Step 1: Create New Spring Project from the menu.

Spring MVC, Spring MVC Project, Spring MVC Example

Step 2: In the new project window, give the name as “SpringMVCExample” and chose template as “Spring MVC Project”. If you are using this template for the first time, STS will download it from SpringSource website. If you want, you can add the project to any working set.

Spring MVC

Spring MVC Template Download, Spring MVC Project, Spring MVC Example

Step 3: When the template is downloaded, in the next screen you need to provide the top-level package name. This package will be used as the base-package for Spring components.

Spring MVC source Package, Spring MVC, Spring MVC Example, Spring MVC Tutorial

Step 4: Once the project is created by Spring MVC template, it will look like below image.

Spring MVC

Don’t worry if you don’t see User.java class, login.jsp and user.jsp files, they have been added by me later on.

If your project is not compiled and you see some errors, run Maven/Update Project. Make sure to check the “Force update of Snapshots/Releases” options, refer below image.

Spring MVC, Maven Force update projects

Overall project looks just like any other maven based web application with some Spring configuration files. Now it’s time to analyze the different part of the projects and extend it a little.

Spring MVC Dependencies

Our generated pom.xml file looks like below.


<?xml version="1.0" encoding="UTF-8"?>
<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.journaldev</groupId>
	<artifactId>SpringMVCExample</artifactId>
	<name>SpringMVCExample</name>
	<packaging>war</packaging>
	<version>1.0.0-BUILD-SNAPSHOT</version>
	<properties>
		<java-version>1.6</java-version>
		<org.springframework-version>4.0.0.RELEASE</org.springframework-version>
		<org.aspectj-version>1.7.4</org.aspectj-version>
		<org.slf4j-version>1.7.5</org.slf4j-version>
	</properties>
	<dependencies>
		<!-- Spring -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${org.springframework-version}</version>
			<exclusions>
				<!-- Exclude Commons Logging in favor of SLF4j -->
				<exclusion>
					<groupId>commons-logging</groupId>
					<artifactId>commons-logging</artifactId>
				 </exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>
				
		<!-- AspectJ -->
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjrt</artifactId>
			<version>${org.aspectj-version}</version>
		</dependency>	
		
		<!-- Logging -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>${org.slf4j-version}</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>jcl-over-slf4j</artifactId>
			<version>${org.slf4j-version}</version>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>${org.slf4j-version}</version>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.15</version>
			<exclusions>
				<exclusion>
					<groupId>javax.mail</groupId>
					<artifactId>mail</artifactId>
				</exclusion>
				<exclusion>
					<groupId>javax.jms</groupId>
					<artifactId>jms</artifactId>
				</exclusion>
				<exclusion>
					<groupId>com.sun.jdmk</groupId>
					<artifactId>jmxtools</artifactId>
				</exclusion>
				<exclusion>
					<groupId>com.sun.jmx</groupId>
					<artifactId>jmxri</artifactId>
				</exclusion>
			</exclusions>
			<scope>runtime</scope>
		</dependency>

		<!-- @Inject -->
		<dependency>
			<groupId>javax.inject</groupId>
			<artifactId>javax.inject</artifactId>
			<version>1</version>
		</dependency>
				
		<!-- Servlet -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>2.5</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet.jsp</groupId>
			<artifactId>jsp-api</artifactId>
			<version>2.1</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>
	
		<!-- Test -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.7</version>
			<scope>test</scope>
		</dependency>        
	</dependencies>
    <build>
        <plugins>
            <plugin>
                <artifactId>maven-eclipse-plugin</artifactId>
                <version>2.9</version>
                <configuration>
                    <additionalProjectnatures>
                        <projectnature>org.springframework.ide.eclipse.core.springnature</projectnature>
                    </additionalProjectnatures>
                    <additionalBuildcommands>
                        <buildcommand>org.springframework.ide.eclipse.core.springbuilder</buildcommand>
                    </additionalBuildcommands>
                    <downloadSources>true</downloadSources>
                    <downloadJavadocs>true</downloadJavadocs>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.5.1</version>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                    <compilerArgument>-Xlint:all</compilerArgument>
                    <showWarnings>true</showWarnings>
                    <showDeprecation>true</showDeprecation>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <version>1.2.1</version>
                <configuration>
                    <mainClass>org.test.int1.Main</mainClass>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

artifactId will be the servlet-context for the web application, so you can change it if you want something else.

There are few properties defined for Spring Framework, AspectJ and SLF4j versions, I found that they were not reflecting the latest versions, so I have changed them to the latest stable version as of today.

The project dependencies that I am interested in are;

  • spring-context: Spring Core dependency. Notice the exclusion of commons logging in favor of SLF4J.
  • spring-webmvc: Spring artifact for MVC support
  • aspectjrt: AspectJ API reference
  • SLF4J and Log4j: For logging purposes, Spring is very easy to configure for log4j or Java Logging API because of SLF4J integration.
  • javax.inject – JSR330 API for dependency injection

There are some other dependencies added, such as Servlet, JSP, JSTL and JUnit API but for starter application, we can overlook them.

Spring MVC Tutorial – Log4j Configuration

The generated log4j.xml file looks like below.


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration PUBLIC "-//APACHE//DTD LOG4J 1.2//EN" "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">

	<!-- Appenders -->
	<appender name="console" class="org.apache.log4j.ConsoleAppender">
		<param name="Target" value="System.out" />
		<layout class="org.apache.log4j.PatternLayout">
			<param name="ConversionPattern" value="%-5p: %c - %m%n" />
		</layout>
	</appender>
	
	<!-- Application Loggers -->
	<logger name="com.journaldev.spring">
		<level value="info" />
	</logger>
	
	<!-- 3rdparty Loggers -->
	<logger name="org.springframework.core">
		<level value="info" />
	</logger>
	
	<logger name="org.springframework.beans">
		<level value="info" />
	</logger>
	
	<logger name="org.springframework.context">
		<level value="info" />
	</logger>

	<logger name="org.springframework.web">
		<level value="info" />
	</logger>

	<!-- Root Logger -->
	<root>
		<priority value="warn" />
		<appender-ref ref="console" />
	</root>
	
</log4j:configuration>

Notice that it’s printing everything to console, we can easily add appenders to redirect logging to files.

Spring MVC Tutorial – Deployment Descriptor Configuration

Let’s see our web.xml and analyze it.


<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 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">

	<!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>/WEB-INF/spring/root-context.xml</param-value>
	</context-param>
	
	<!-- Creates the Spring Container shared by all Servlets and Filters -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

	<!-- Processes application requests -->
	<servlet>
		<servlet-name>appServlet</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
		
	<servlet-mapping>
		<servlet-name>appServlet</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>

</web-app>

ContextLoaderListener ties the ApplicationContext lifecycle to ServletContext lifecycle and automate the creation of ApplicationContext. ApplicationContext is the place for Spring beans and we can provide it’s configuration through contextConfigLocation context parameter. root-context.xml file provides the configuration details for WebApplicationContext.

DispatcherServlet is the controller class for Spring MVC application and all the client requests are getting handled by this servlet. The configuration is being loaded from the servlet-context.xml file.

Spring MVC Tutorial – Configuration Files

root-context.xml file:


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	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.xsd">
	
	<!-- Root Context: defines shared resources visible to all other web components -->
		
</beans>

We can define shared beans here, as of now there is nothing in it.

servlet-context.xml code:


<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:beans="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

	<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
	
	<!-- Enables the Spring MVC @Controller programming model -->
	<annotation-driven />

	<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
	<resources mapping="/resources/**" location="/resources/" />

	<!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
	<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<beans:property name="prefix" value="/WEB-INF/views/" />
		<beans:property name="suffix" value=".jsp" />
	</beans:bean>
	
	<context:component-scan base-package="com.journaldev.spring" />	
	
</beans:beans>

This is how the standard Spring configuration file looks like, just imagine writing all this on your own and you will start liking STS tool.

annotation-driven element is used to let Controller servlet know that annotations will be used for bean configurations.

resources element defines the location where we can put static files such as images, HTML pages etc that we don’t want to get through Spring framework.

InternalResourceViewResolver is the view resolver, we can provide view pages location through prefix and suffix properties. So all our JSP pages should be in /WEB-INF/views/ directory.

context:component-scan element is used to provide the base-package location for scanning Controller classes. Remember the value of the top-level package given at the time of project creation, it’s the same value getting used here.

Spring MVC Controller Class

HomeController is created automatically with the home() method, although I have extended it a little bit by adding loginPage() and login() methods.


package com.journaldev.spring;

import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * Handles requests for the application home page.
 */
@Controller
public class HomeController {
	
	private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
	
	/**
	 * Simply selects the home view to render by returning its name.
	 */
	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String home(Locale locale, Model model) {
		logger.info("Welcome home! The client locale is {}.", locale);
		
		Date date = new Date();
		DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
		
		String formattedDate = dateFormat.format(date);
		
		model.addAttribute("serverTime", formattedDate );
		
		return "home";
	}
	
	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String loginPage(Locale locale, Model model) {
		return "login";
	}
	
	@RequestMapping(value = "/home", method = RequestMethod.POST)
	public String login(@Validated User user, Model model) {
		model.addAttribute("userName", user.getUserName());
		return "user";
	}
}

@Controller annotation is used to indicate that it’s a web controller class.

@RequestMapping is used with classes and methods to redirect the client request to specific handler method. Notice that handler methods are returning String, this should be the name of view page to be used as the response.

As you can see that we are having three methods returning different strings, so we need to create JSP pages with the same name.

Notice that login() method will get called with HTTP method as POST, so we are expecting some form data here. So we have User model class and it’s marked for validation using @Validated annotation.

Every method contains Model as an argument and we can set attributes to be later used in the JSP response pages.

Spring MVC Model Classes

Model classes are used to hold form variables, our User model bean looks like below.


package com.journaldev.spring;

public class User {

	private String userName;

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}
	
}

A simple java bean with the variable name and its getter and setter methods.

Spring MVC Tutorial – View Pages

We have three JSP pages like below.

home.jsp code:


<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" %>
<html>
<head>
	<title>Home</title>
</head>
<body>
<h1>
	Hello world!  
</h1>

<P>  The time on the server is ${serverTime}. </P>
</body>
</html>

Notice the use of JSP Expression Language to get the attribute values.

login.jsp code:


<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Login Page</title>
</head>
<body>
<form action="home" method="post">
<input type="text" name="userName"><br>
<input type="submit" value="Login">
</form>
</body>
</html>

A simple JSP page for the user to provide the userName as input. Notice that form variable name is same as User class variable name. Also, form action is “home” and method is “post”. It’s clear that HomeController login() method will handle this request.

user.jsp code:


<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>User Home Page</title>
</head>
<body>
<h3>Hi ${userName}</h3>
</body>
</html>

Simple home page for the user where username is displayed, notice that we are setting this attribute in the login method.

Spring MVC Example Application Testing

Our application is ready for execution, just run it on the VMware tc Server or your choice of any other servlet container, you will get below pages as the response.

Spring MVC Hello World, Spring MVC, Spring MVC Example

Spring MVC Hello World, Spring MVC

Spring MVC Hello World, Spring MVC Tutorial

That’s it for Spring MVC Tutorial, you can see that how easy it is to create Spring MVC application using STS plugins. The code size is very less and most of the configuration is handled by Spring MVC so that we can focus on business logic. Download the example spring MVC project from below link and play around with it.

Comments

  1. Krutik says:

    Hi Pankaj,

    Thanks a lot for your awesome content.

    I am facing one issue though while following this tutorial, While I am deploying the application from the STS itself then it’s not returning me any content for the URL ping: http://localhost:8080/demo/

    But if I put the war file generated in the tomcat webapps directory and run the tomcat from the outside of STS by running startup.bat file and then ping the above URL then it works fine.

    Please let me know the reason behind this.

    Thanks,
    Krutik

    1. Pankaj says:

      The reason might be the WAR file name getting deployed in the embedded Tomcat in STS.

  2. ram says:

    Every thing is easy to understand..Thanks for knowledge sharing..it works well …

  3. Ankush Khandelwal says:

    Just followed the tutorial as it is on STS-Java 8
    I got “http://localhost:8080/spring/” running and showing results as:
    Hello world!
    The time on the server is 11 February 2019 10:07:37 PM IST.

    but
    http://localhost:8080/SpringMVCExample/login
    doesn’t work… I get 404 error… there looks to be some issue with the context configurations. please help..
    HTTP Status 404 – Not Found

    ——————————————————————————–

    1. Pankaj says:

      You have mentioned the fix in your comment. Notice that the application context is /spring in your case. So just change the URL to http://localhost:8080/spring/login and it should work fine.

      1. Nisha gogia says:

        Hi sir,

        I am facing the same error.I have followed the same steps,even the name of the app is the same.But when I run login.jsp it gives 404 error.But when globally run the project using http://localhost:8080/SpringMVCExample/login it runs fine!Please help me with the issue

  4. parsa says:

    If I wanna create MVC project in IntelliJ what should I do?

  5. DJ says:

    Is there something wrong in the context? It is giving me 404 error. I checked the war file name being created (SpringMVCExample-1.0.0-BUILD-SNAPSHOT) and add that to context in the browser. I.e http://localhost:8080/SpringMVCExample-1.0.0-BUILD-SNAPSHOT/ and it still gave me 404 error. Could you please check?

  6. subarashi says:

    i imported the downloaded zip file in STS and then selected run on server and then this error comes. what is this WAR file you keep on talking about i dont see any WAR file here ? do i have to export this project ? or something ?

    I get the same error in the spring rest api tutorial when i download and import the project in STS.

    HTTP Status 404 – Not Found

    ——————————————————————————–

    Type Status Report

    Message /SpringMVCExample/

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

    1. Pankaj says:

      Just build the maven project and deploy the WAR file to Tomcat. Check the WAR file name being deployed, that will become the context of your web app.

  7. Gaurav Dalal says:

    Created project as it is but getting 404 –http://localhost:8080/webproject/WEB-INF/views/home.jsp

    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.

    USing
    Java 8
    STS – Latest Version

    This error has been bugging, started reading this tutorial with lot enthusiasm but now feeling lost.

    I followed everything step by step, still not sure where I going wrong. Need Help.

    1. Pankaj says:

      Can you please check what is the WAR file name? If war file name is xyz.war then the application context will be /xyz. That means you can access the page at http://localhost:8080/xyz/WEB-INF/views/home.jsp

      404 error means not found, usually the application context is the issue.

  8. Priyanshu joshi says:

    enjoyed your tutorial . thanks for making it .

  9. Ranjan says:

    Hi Pankaj,

    I am going through both the application structures spring and spring mvc. can you tell me the difference in configuration files in both.

    For standalone spring application i find spring bean configuration files but for spring mvc the configuration files are different.

    please clarify this thing

    1. Pankaj says:

      When you are using only Spring Core Framework, you specify the spring beans in the configuration file. But when you are using Spring MVC, you need to configure it in the web.xml file. Also, you need to specify some extra things, such as InternalResourceViewResolver, resources etc.

  10. SHOBHIT says:

    Hi Pankaj,

    I was struggling since days to add external css/js files to spring.
    This has been very helpful.
    Thanks.

  11. Benjamin says:

    Are this tutorial actually?
    Because i tried to create the project from step 1 in eclipse with the STS extension and in the STS.

    In STS i cannot create a Spring Legacy Project (there is no Spring Project) because he is refreshing something – i dont know what but it tooks now over 10 minutes. So there is no order “Persistance” with Spring MVC Project.

    In Eclipse i can create the Project, with build errors:
    Errors running builder ‘Maven Project Builder’ on project ‘SpringMVCExample’.
    Could not calculate build plan: Plugin org.apache.maven.plugins:maven-resources-plugin:2.6 or one of its dependencies could not be resolved: Failed to read artifact descriptor for org.apache.maven.plugins:maven-resources-plugin:jar:2.6

    Plugin org.apache.maven.plugins:maven-resources-plugin:2.6 or one of its dependencies could not be resolved: Failed to read artifact descriptor for org.apache.maven.plugins:maven-resources-plugin:jar:2.6
    Could not calculate build plan: Plugin org.apache.maven.plugins:maven-resources-plugin:2.6 or one of its dependencies could not be resolved: Failed to read artifact descriptor for org.apache.maven.plugins:maven-resources-plugin:jar:2.6

    Plugin org.apache.maven.plugins:maven-resources-plugin:2.6 or one of its dependencies could not be resolved: Failed to read artifact descriptor for org.apache.maven.plugins:maven-resources-plugin:jar:2.6

    So, i tried to update the project as descriped above but then i become the same errors.

    Using Software:
    STS 3.9.0
    Eclipse Neo.3

    May someone can help me ?

    1. Pankaj says:

      Please use this tutorial for beginners using Eclipse.

      Spring MVC Example

  12. Ketan Prajapati says:

    Issue: The import org.springframework.web.bind cannot be resolved

    Solution : pom.xml updated with below dependency

    org.springframework
    spring-webmvc
    4.3.3.RELEASE

  13. Tania says:

    Only SpringMVC example that worked for me. Thank you for this tutorial!

  14. sidiya says:

    Great tutorial, learned a lot with simple example. but i have this error can you helpe me please !!! things

    Failure to transfer org.apache.maven.plugins:maven-surefire-plugin:pom:2.12.4 from http://repo.maven.apache.org/maven2 was cached in the local repository,
    resolution will not be reattempted until the update interval of central has elapsed or updates are forced. Original error: Could not transfer artifact
    org.apache.maven.plugins:maven-surefire-plugin:pom:2.12.4 from/to central (http://repo.maven.apache.org/maven2): repo.maven.apache.org

    1. Pankaj says:

      Do a clean build in Eclipse with Force Update or through terminal mvn clean install -U

  15. prade says:

    great and appreciated ;
    very easy to understand example

  16. Ashish says:

    hi pankaj……
    My spring boot Application running on local tomcat ,,, but when it deploy on remote server for hosting then not running ……..could you help me come out from this problem

  17. Jyothi says:

    Hi,
    I want to access data from the api in json objects and do the operations in controllers.
    can i do that??

  18. Abhishek S says:

    Great explanation…

    Can you please explain me how to add external css and js files to this project…

    Thanks…

    1. Pankaj says:

      CSS and JS files are used in client side, you can add them in JSP pages just like HTML pages.

  19. Krunal Shah says:

    Nice explanation.

    Thanks,
    Krunal

  20. Vikas Bhardwaj says:

    And instead of reply make some thing so we can show our error with pages so we can get the solution after trying these tutorial wtw asm tutorial thanks a lot..

    1. Pankaj says:

      Hi Vikas,

      You can upload the project or share it with me through email. For errors, you can upload screenshot to any of free image hosting websites and post the link.

  21. Vikas Bhardwaj says:

    Login Page

    i just change the jsp tag with spring tag but it give me error

    WARN : org.springframework.web.servlet.PageNotFound – No mapping found for HTTP request with URI [/controller/] in DispatcherServlet with name ‘appServlet’

    1. Vikas Bhardwaj says:

      every time when i use the spring tag instead of jsp tag it gives me the same error

      Login Page

      1. Pankaj says:

        Could you please provide the code you changed? Please wrap them inside pre tags to avoid being treated as HTML page and eaten up by browser.

  22. Patricia says:

    Great! Thank you for this tutorial!

    1. Pankaj says:

      you are welcome Patricia.

  23. jorge says:

    This tutorial is very good!
    and thanks for the code to download!

    please keep doing more of these

    1. Pankaj says:

      All my projects are free to download, thanks for the appreciation.

  24. chandra sekhar says:

    Great work..thanks a ton

    1. Pankaj says:

      you are welcome chandra.

  25. sarvesh says:

    great tutorials………thank you so much…..

    1. Pankaj says:

      you are welcome Sarvesh, thanks for the comment.

  26. karablaxos says:

    Hi Pankaj
    Can you explain why from variable name must be the same as User class variable name?

    1. Pankaj says:

      so that Spring can map UI form data to spring bean.

  27. Mohd Raisuddin says:

    Sir,
    what is maven and what is dependency , why we use it and how it works
    plz tell me

    1. Pankaj says:

      Maven is a build management tool, used to manage dependencies and build JAR, WAR files.

  28. mk says:

    thnx a lot .it helps me a lot …

  29. Kaveen says:

    Hi Pankaj.

    Great tutorial .Could you please explain more about model class and handler methods.?

    1. Pankaj says:

      Go through my Spring tutorials, I have explained all these in more detail in other articles.

  30. Ravikumar says:

    Thanks a alot

  31. Diwakar says:

    I am able to access http://localhost:8080/springMVCExample/, but when i try to access the login page http://localhost:8080/springMVCExample/login get HTTP 404 error

    Is there any settings i need to change.

    Thanks for the tutorial.

    1. Vu Le says:

      You should check login.jsp again,

    2. victor márquez says:

      sometimes ned ti restar eclipse or exit an entry again

    3. Rajesh Pendela says:

      Just go to windows->show views -> server there you will see the server.
      Double click on that and open the modules. there you can see the path. that is the real path for your application.

      you can see the path like /spring

      In my case, my path is localhost:8080/spring

      1. André Maciel says:

        This comment was great. Thank you.

      2. Mark Lally says:

        This helped a lot, cheers Rajesh!

  32. Bill Hopkins says:

    Excellent tutorial – thanks so much for sharing it.

    1. Pankaj says:

      you are welcome Bill

  33. Vibinchander says:

    Hi,
    Im just now learning spring. My aim is to create RESTful web services using SPRING. In case if im not using spring, just with eclipse IDE, i can create dynamic web application and run it on local host server like tomcat.

    Even then, i will get the required URL in the top. Can’t we call it as REST service?. Why do we want to use SPRING to generate a Dynamic Web application?….

    Please educate me.

    1. Pankaj says:

      We are using IDE to generate web application to get the skeleton of the project and then build on top of it.

  34. PA says:

    Hi Pankaj – Could you please create “Spring MVC Swagger” example? You’ve lots of different types of example codes, but I don’t see it “Spring MVC Swagger”. That would really help for all your followers who re following you from most of the years.

    Thanks

    1. Pankaj says:

      I have never used it, that’s why I have not posted about it. Check below StackOverflow link, it has some good information.

      http://stackoverflow.com/questions/26720090/a-simple-way-to-implement-swagger-in-a-spring-mvc-application

  35. Pabel Lopez says:

    I found a typo

    Spring Controller Class

    HelloController >> should be HomeController.

    Thank you for this tutorial 😀

    1. Pankaj says:

      Thanks Pabel, I have corrected it.

  36. Fazin says:

    Thanks for the tutorial….Pls tell me why i am not getting the value in user.jsp ; instead it shows ‘hi’ only…i checked literally everything….

    1. Pankaj says:

      Obviously there is some issue in your code, please use logger to check whether u have value in the Controller class and then check for any typos etc.

      1. Erhan says:

        First of all thank you for this helpful tutorial. I fixed this problem by changing EL in user.jsp page to ${param.userName}.

  37. Bhupinder Singh says:

    Pankaj,

    I just want say big thanks to you for all yours wonderful blogs. These are very simple to follow as compare to other blogs. You are doing great job keep it up.

    Regards
    Bhupinder

    1. Pankaj says:

      You just made my day brother. 🙂

  38. emoleumassi says:

    Very nice tutorial. It’s working fine for me. But i’ve one question: how can i separate the datasource and hibernate configuration from the servlet-context. I mean, i had created two extra files:
    datasource.xml:

    properties/database.properties

    and hibernate.xml:

    com.journaldev.spring.model.Person

    org.hibernate.dialect.MySQLDialect

    true

    How can i import/integrated those files in servlet-context?
    Cheers

    1. Pankaj says:

      Use the import tag to load multiple resources.

  39. Raju says:

    Hi Pankaj, Thanks for the great tutorial. I could never understand one thing –

    Spring Controller methods accepts any combination of parameters, regardless of type and count.
    How this happens? Why there is not standard rule for this.

    Who passes the values for these parameters ?

    and also, how should we plan what argument to take while designing those methods?

    Thanks,
    Raju.

    1. Pankaj says:

      Its all possible because of Reflection and Annotations.

  40. Rizwan Mursaleen says:

    Thanks. It was straight forward and easy to follow.

  41. Nam G VU says:

    How to customize startup URL when running a Spring MVC web application in STS?

    I’m following your tutorial and succeeded to get the sample application run from springsource’s STS IDE.

    Though when started, the initial URL opened is

    http://localhost:8080/springmvc/WEB-INF/views/home.jsp

    which need to be corrected as below as I want to run the default Home controller.

    http://localhost:8080/springmvc/

    How can I change that startup URL when run?

    This question is also posted on stackoverflow.com at http://stackoverflow.com/questions/26386462/how-to-customize-startup-url-when-running-a-spring-mvc-web-application-in-sts

  42. Gigi Sapun says:

    Thank you for this tutorial and for your site. You are very helpful!

  43. Abhiroop says:

    Really a very good tutorial implementing the new STS tool and spring. Most of the tutorials online are very old. Thanks again. Keep up this great work!!!

  44. Ganesh says:

    I am getting error in root-context.xml and pom.xml

  45. Ajaya Kumar says:

    Hi All,

    I am getting below error.please help me how to resolve this problem.

    org.springframework.web.servlet.PageNotFound – No mapping found for HTTP request with URI [/spring/] in DispatcherServlet with name ‘appServlet’

    I am using JDK 1.6, tomcat 7

    1. Pankaj says:

      What is the WAR file name that you have deployed in Tomcat7, that will be your application context. I think that’s why it’s not working for you.

      1. Steve says:

        You could run through how to compile this project too, you asume too much, there is no WAR file at the stage you finnish this project

        1. Steve says:

          HTTP Status 404 – /SpringMVCExample/

          type Status report

          message /SpringMVCExample/

          description The requested resource is not available.

          Apache Tomcat/8.0.12

        2. Pankaj says:

          Hi Steve,

          If you are learning Spring, I am sure you can run mvn clean install command in the terminal to build your project WAR and then copy it to your tomcat webapps directory. Also you should know that the file name will be the Servlet Context of the application. This tutorial is not intended to include everything, if I include every minor details, it will become a large book.

    2. Srikanth Kattam says:

      Hi Ajaya Kumar,

      Please check your HomeController.java class has proper @RequestMapping.

      Thanks

  46. Raghav says:

    Hello Pankaj,

    I am getting an error in servlet-context.xml (line:13

    Class ‘org.springframework.web.servlet.config.AnnotationDrivenBeanDefinitionParser
    $CompositeUriComponentsContributorFactoryBean’ not found [config set: SpringMVCExample/web-context]

    How to correct it.

    Thanks & Regards,
    Raghav

    1. Farago says:

      hello, i met the same problem but have no idea how to solve it.
      have you fixed it?

  47. Gilbert says:

    Hi, Pankaj. I’m a beginner of spring mvc. I can’t understand how is the textbox value “userName” in user.jsp saved to User. The value must be recorded to User class somewhere so that in HomeController.java you can set the model’s attribute “userName” with user.getUserName(), but I can’t find where.

    1. xyz says:

      thank u bhaii…

  48. Lary says:

    Thanks Pankaj. a very insightful example.

    I know this might be a stupid question; please what is the difference between springsource tc server and vmware vfabric tc server?

    Also I have successfully installed STS into my Eclipse environmnt but I am having issues adding springsource tc server 2.1 to my project; at the point where it’s asking for installation directory, if i click on Browse, i am unable to find anything as i dont know where STS installation dumped the require file

    Thanks as you help

  49. Sandeep says:

    Excellent tutorial Pankaj!!

  50. siva says:

    nicely helped me to learn

  51. Hussam says:

    I am a very beginner using STS.

    I followed all the steps in building the project on my STS.
    but, when I run it using WMware vFabric tc Server v2.5 , the server runs correctly, and I can browse to the home page. but when I type the URL of the project as it shown in the pictures you provide in this doc. it show me error. means that there is no page with this name.

    second, can you tell me how to import the project to STS without the need to rebuild it step by step?

    My best regards

    1. Pankaj says:

      1. It’s because when you deploy from STS, it automatically generates a context file with name “spring”, so you should use it like that. I am sure you know about web application servlet context.

      2. STS is built on top of Eclipse, so you can import any project like you do in Eclipse.

  52. Rakesh Konda says:

    Too good. Excellently written and excellently detailed.
    Pankaj, you should definitely start online video tutorials too.

    Thanks a lot for posting such a valuable thing for us

    Thanks
    -Rakesh

  53. Suma says:

    God bless u !!!
    Thank u for the wonderful tutorial. It really helps students like me.

  54. Prashanth says:

    Hi Pankaj

    God Bless you..You are the best, very helpful for a learner like me.

    regards,
    Prashanth

  55. Marcel says:

    Great tutorial, Pankaj.
    Is helping me a lot.
    Thanks!

  56. Nathi Heimoski says:

    Very nice explanation! worked perfectly! great tutorial!! 🙂

  57. Nitin says:

    In Login page, after clicking on Login button, it not redirecting to home page. Its prompting error like below…

    SOURCES
    Deployment url : http://localhost:8080/test/home

    ERROR SUMMARY
    Below is a summary of the errors, details of these errors are listed later in the log.
    * Activation of http://localhost:8080/test/home resulted in exception. Following failure messages were detected:
    + Downloading http://localhost:8080/test/home did not succeed.
    + The remote server returned an error: (405) Method Not Allowed.
    Please help…

    1. Pankaj says:

      Which browser you are using?

  58. ketan says:

    sir i didn’t get the login page .. only home page appear after the server starts …

    wating for ur reply ..

    sir i m using macbook .
    tell me how to connect mysql with STS …

    thank you sir ..

    god bless you sir for ur efforts .. 🙂

    1. Pankaj says:

      Check the image URL for the URI pattern to use in your application for login page. If you are using Macbook Pro, you can download “Sequel Pro” that is a very good IDE for MySQL databases.

      1. ketan says:

        thank you very much sir …!

  59. Suresh says:

    I got this running only when I give “http://localhost:8080/spring/” instead of giving
    “http://localhost:8080/springMVCExample/”.

    Where am I going wrong?

    1. Pankaj says:

      That’s because STS tcserver automatically creates a context.xml file for the application with ServletContext as spring. You can check that in the tcserver directories.

      1. Rohan says:

        I am able to access http://localhost:8080/spring/, but when i try to access the login page http://localhost:8080/spring/login get HTTP 404 error

        Is there any settings i need to change

        Thanks

      2. Hussam says:

        I have the same problem.
        but how to create my own context.xml

        ?
        with many thanks

        1. Pankaj says:

          Don’t run from Eclipse, export as WAR file and then deploy it.

    2. John Britto says:

      Not sure if this is proper etiquette or not — I am editing this answer to give exact steps for Eclipse Indigo.

      1. In your project’s Properties, choose “Web Project Settings”.

      2. Change “Context root” to “app”.

      3. Choose Window > Show View > Servers.

      4. Stop the server by either clicking the red square box (“Stop the server” tooltip) or context-click on the server listing to choose “Stop”.

      5. On the server you want to use, context-click to choose “Clean…”.

      6. Click OK in this confirmation dialog box.

      Screenshot of dialog asking to update server configuration to match the changed context root

      Now you can run your app with the new “app” URL such as:

      http://localhost:8080/app/

  60. Kofi says:

    Thanks Pankaj. Was very useful. As you are doing good, my prayer for you is to give your life to Jesus Christ and pursue eternal life through him. This is not a joke or a laughing mater. Thanks again.

  61. Sandipon Saha says:

    how to call setUserName mehods

  62. Sandipon Saha says:

    how to call setUserName(String userName)

    1. Pankaj says:

      Its automatically called by Spring framework. Ultimately it’s a normal Java Bean and if you have the object, you can call the method and set any value you want.

  63. Reddy says:

    Really helpfull…

  64. Ganesh Dudhade says:

    when i import this project i found following error:
    java.lang.ClassCastException: org.apache.jasper.el.ELContextImpl cannot be cast to org.apache.jasper.el.ELContextImpl

    waiting for reply…….
    thnx

    1. Pankaj says:

      Are you getting compile time error or at runtime. I think it’s because of Classloading issue since the both classes names are same. Are you running on Tomcat or STS Server?

      Please check your project settings.

  65. Mohanakrishnan Sudersan says:

    Good work,.
    Highly appreciate the efforts.

  66. Sreeni says:

    Very nice explanation , thank u so much….

  67. Rajesh says:

    Great tutorial, learned a lot with simple example.

    Looking forward for Spring Webservices and Rest tutorials, keep them coming.

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages