Spring MVC Hello World project


Tools and Technologies used


1) Eclipse IDE Mars Release (4.5.0)

2) Java 8

3) Spring framework 4.2

4) Tomcat 8

Right click on project explorer and select New Project

SpringMVCHelloWorld_createProj1

Select maven project and click on Next

SpringMVCHelloWorld_createProj2

Click on Next and select maven web app archetype

SpringMVCHelloWorld_createProj3

Enter archetype parameters as below and click on Finish

SpringMVCHelloWorld_createProj4

Now the Project Structure in eclipse should be

SpringMVCHelloWorld_ProjectStructure-1

Create Spring configuration file

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
  4.     xmlns:context="http://www.springframework.org/schema/context"
  5.     xmlns:mvc="http://www.springframework.org/schema/mvc"
  6.     xsi:schemaLocation="http://www.springframework.org/schema/beans
  7.        http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
  8.        http://www.springframework.org/schema/context
  9.        http://www.springframework.org/schema/context/spring-context-3.2.xsd
  10.        http://www.springframework.org/schema/mvc
  11.        http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
  12.  
  13.     <context:component-scan base-package="com.kb.*" />
  14.     <mvc:annotation-driven />
  15.      
  16.     <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  17.         <property name="prefix" value="/WEB-INF/pages/" />
  18.         <property name="suffix" value=".jsp" />
  19.     </bean>
  20. </beans>
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    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/context
        http://www.springframework.org/schema/context/spring-context-3.2.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
 
    <context:component-scan base-package="com.kb.*" />
    <mvc:annotation-driven />
     
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/" />
        <property name="suffix" value=".jsp" />
    </bean>
</beans>


< context:component-scan > tag specifies the packages to be scanned for the spring beans.
So when spring gets loaded , it searches for all the spring beans inside the package specified in the base-package attribute.

Here I have given as com.kb.* , here it represents all the classes which comes under any folder inside com/kb.
So our controller is kept inside com/kb/controllers package to let the spring know it.

View Resolver is used to specifies how the absolute path of view returned in the controller can be obtained.
It specifies prefix and suffix.
In our case , prefix is WEB-INF/pages and suffix is .jsp

So any string returned from the controller is followed with this prefix and suffix before rendering.

From HelloWorldController we are returning /helloworld,
So with the help of view resolver defined, it becomes prefix+/helloworld+suffix
That is WEB-INF/pages/helloworld.jsp
So this jsp page is going to be displayed when we call this controller.

Modify web.xml as below

  1. <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2.     xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
  3.     version="3.1">
  4.  
  5.   <display-name>Archetype Created Web Application</display-name>
  6.  
  7.   <!-- Spring MVC dispatcher servlet -->
  8.     <servlet>
  9.         <servlet-name>mvc-dispatcher</servlet-name>
  10.         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  11.         <init-param>
  12.             <param-name>contextConfigLocation</param-name>
  13.             <param-value>
  14.             /WEB-INF/spring-mvc.xml
  15.             </param-value>
  16.         </init-param>
  17.         <load-on-startup>1</load-on-startup>
  18.     </servlet>
  19.     <servlet-mapping>
  20.         <servlet-name>mvc-dispatcher</servlet-name>
  21.         <url-pattern>/</url-pattern>
  22.     </servlet-mapping>
  23.  
  24.     <listener>
  25.         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  26.     </listener>
  27.     <!-- Loads Spring Security configuration file -->
  28.     <context-param>
  29.         <param-name>contextConfigLocation</param-name>
  30.         <param-value>
  31.             /WEB-INF/spring-mvc.xml
  32.         </param-value>
  33.     </context-param>
  34. </web-app>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
	version="3.1">

  <display-name>Archetype Created Web Application</display-name>
  
  <!-- Spring MVC dispatcher servlet -->
	<servlet>
		<servlet-name>mvc-dispatcher</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>
			/WEB-INF/spring-mvc.xml
			</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>mvc-dispatcher</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>

	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	<!-- Loads Spring Security configuration file -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>
			/WEB-INF/spring-mvc.xml
		</param-value>
	</context-param>
</web-app>


Add Spring mvc dispatcher servelet to enable the spring mvc framework
and add listener and filename to load the spring configuration file.

Modify pom.xml to have spring mvc dependencies as below

  1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2.     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  3.     <modelVersion>4.0.0</modelVersion>
  4.     <groupId>SpringProject</groupId>
  5.     <artifactId>SpringMVCHelloWorld</artifactId>
  6.     <packaging>war</packaging>
  7.     <version>0.0.1-SNAPSHOT</version>
  8.     <name>SpringMVCHelloWorld Maven Webapp</name>
  9.     <url>http://maven.apache.org</url>
  10.     <properties>
  11.         <org.springframework.version>4.2.0.RELEASE</org.springframework.version>
  12.     </properties>
  13.     <dependencies>
  14.         <dependency>
  15.             <groupId>junit</groupId>
  16.             <artifactId>junit</artifactId>
  17.             <version>3.8.1</version>
  18.             <scope>test</scope>
  19.         </dependency>
  20.         <!-- Spring MVC depends on these modules spring-core, spring-beans, spring-context,
  21.             spring-web -->
  22.         <dependency>
  23.             <groupId>org.springframework</groupId>
  24.             <artifactId>spring-web</artifactId>
  25.             <version>${org.springframework.version}</version>
  26.         </dependency>
  27.  
  28.         <dependency>
  29.             <groupId>org.springframework</groupId>
  30.             <artifactId>spring-webmvc</artifactId>
  31.             <version>${org.springframework.version}</version>
  32.         </dependency>
  33.     </dependencies>
  34.     <build>
  35.         <finalName>SpringHelloWorld</finalName>
  36.         <plugins>
  37.             <plugin>
  38.                 <groupId>org.apache.maven.plugins</groupId>
  39.                 <artifactId>maven-compiler-plugin</artifactId>
  40.                 <version>2.5.1</version>
  41.                 <configuration>
  42.                     <source>1.8</source>
  43.                     <target>1.8</target>
  44.                 </configuration>
  45.             </plugin>
  46.         </plugins>
  47.     </build>
  48. </project>
<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>SpringProject</groupId>
	<artifactId>SpringMVCHelloWorld</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>
	<name>SpringMVCHelloWorld Maven Webapp</name>
	<url>http://maven.apache.org</url>
	<properties>
		<org.springframework.version>4.2.0.RELEASE</org.springframework.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>3.8.1</version>
			<scope>test</scope>
		</dependency>
		<!-- Spring MVC depends on these modules spring-core, spring-beans, spring-context, 
			spring-web -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>${org.springframework.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${org.springframework.version}</version>
		</dependency>
	</dependencies>
	<build>
		<finalName>SpringHelloWorld</finalName>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>2.5.1</version>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>


Now create a new folder ‘java’ inside src/main folder

SpringMVCHelloWorld_createProj5

SpringMVCHelloWorld_createProj6

SpringMVCHelloWorld_createProj7

Now create a class called Hello World Controller inside controller package

SpringMVCHelloWorld_createclass1

SpringMVCHelloWorld_createclass2

HelloWorldController class should be as below

  1. package com.kb.controllers;
  2.  
  3. import org.springframework.stereotype.Controller;
  4. import org.springframework.ui.Model;
  5. import org.springframework.web.bind.annotation.RequestMapping;
  6.  
  7.  
  8. @Controller
  9. @RequestMapping("/pages")
  10. public class HelloWorldController {
  11.  
  12.     @RequestMapping("/helloWorld")
  13.     public String helloWorld(Model model) {
  14.        
  15.         model.addAttribute("message", "Hi user, Great !! , welcome to First Spring MVC project");
  16.  
  17.         return "/helloWorld";
  18.     }
  19.  
  20. }
package com.kb.controllers;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;


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

	@RequestMapping("/helloWorld")
	public String helloWorld(Model model) {
		
		model.addAttribute("message", "Hi user, Great !! , welcome to First Spring MVC project");

		return "/helloWorld";
	}

}

Now create a new folder ‘pages’ inside WEB-INF

Now create a helloWorld.jsp inside pages folder

SpringMVCHelloWorld_createjsp1

SpringMVCHelloWorld_createjsp2

helloWorld.jsp

  1. <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
  2.     pageEncoding="ISO-8859-1"%>
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  4. <html>
  5.   <head>
  6.      <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
  7.      <title>Hello World</title>
  8.   </head>
  9.   <body>
  10.      <h4>${message}</h4>
  11.   </body>
  12. </html>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
     <title>Hello World</title>
  </head>
  <body>
     <h4>${message}</h4>
  </body>
</html>


Now the application is ready, Lets Build and Deploy it.

Build

Right click on the project and select Run As maven install

SpringMVCHelloWorld_createProj_Build

Below output in the console should appear with success status

Now the war file is copied into the target folder of the project.

Deployment

Add Tomcat server in your eclipse
Right click on Server window in eclipse and click on select server.
Give server details

SpringMVCHelloWorld_Project_servers

Copy the war file from project target location

SpringMVCHelloWorld_Project_war

Paste it in the Tomcat webapps directory

In my system it is
E:\java\apache-tomcat-8.0.5-windows-x64\apache-tomcat-8.0.5\webapps

SpringMVCHelloWorld_Project_warPasted

Now deployment is done.

Let’s start the server
Go to server tab inside eclipse and right click on it and click on start

SpringMVCHelloWorld_Project_Startserver

Now server should be started with no errors in the console

SpringMVCHelloWorld_Project_serverstartedSuccessfully

Lets run the application

http://localhost:8080/SpringHelloWorld/pages/helloWorld

SpringMVCHelloWorld_ProjectOutput

Download this project SpringMVCHelloWorld.zip

About the Author

Founder of javainsimpleway.com
I love Java and open source technologies and very much passionate about software development.
I like to share my knowledge with others especially on technology 🙂
I have given all the examples as simple as possible to understand for the beginners.
All the code posted on my blog is developed,compiled and tested in my development environment.
If you find any mistakes or bugs, Please drop an email to kb.knowledge.sharing@gmail.com

Connect with me on Facebook for more updates

Share this article on