Spring MVC hello world example

In this post, we will see Spring MVC hello world example using maven.

Spring MVC tutorial:

    Spring MVC hello world example Spring MVC Hibernate MySQL example Spring MVC interceptor example Spring MVC angularjs example Spring MVC @RequestMapping example Spring Component,Service, Repository and Controller example Spring MVC @ModelAttribute annotation example Spring MVC @RestController annotation example Spring MultiActionController Example Spring MVC ModelMap Spring MVC file upload example Spring restful web service example Spring restful web service json example Spring Restful web services CRUD example Spring security hello world example Spring security custom login form example
Tools used for this post are:
  • Eclipse
  • Maven plugin(m2eclipse)
  • JDK 1.7
  • Apache tomcat 8

Steps for creating Spring MVC hello world example.


1) Install m2eclipse for maven plugin in eclipse. Please follow this link for installing m2eclipse plugin in eclipse.

2) goto new -> project-> Maven Project and click on next

3) You will see below screen , again click on next


4) We need to select type of archetype here.As we are creating web app here, please put following text in filter : maven-archetype-webapp



5) We need to put group id and artifact id here.

Let me tell you more about group id and artifact id.

Group id : It uniquely identifies your project among all. So it may be something like com.companyname

Artifact id : It is name of jar or war without version. it may be something like project, so here we have put artifact id as mavenWebApp

Version : Version is used for version control for artifact id. If you distribute this project, you may incrementally create different version of it.


When you follow above steps, your project structure will look like below:
As you can see, we are getting an error ("The superclass "javax.servlet.http.HttpServlet" was found in java build path") in index.jsp. 
To solve this issue, follow below steps:
you need to set target run time as Apache tomcat. To do that,right click on project -> properties -> target runtimes



Adding Spring MVC dependency

6) Add spring dependency in pom.xml. We require spring core and spring mvc dependency here.

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.arpit.java2blog</groupId>
  <artifactId>SpringMVCHelloWorldExample</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>SpringMVCHelloWorldExample 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>javax.servlet</groupId>
     <artifactId>javax.servlet-api</artifactId>
     <version>3.1.0</version>
   </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>SpringMVCHelloWorldExample</finalName> 
    
    <plugins>
        <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.1</version>
        <configuration>
            <source>${jdk.version}</source>
            <target>${jdk.version}</target>
        </configuration>
    </plugin>
    </plugins>

  </build>
   <properties>
  <spring.version>4.2.1.RELEASE</spring.version>
  <jdk.version>1.7</jdk.version>
   </properties>
</project>

Create Controller  and view

7) Create a package named "org.arpit.java2blog.springmvc.controller"
create a controller class named "HelloWorldController.java"
package org.arpit.java2blog.springmvc.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class HelloWorldController {
 
 @RequestMapping("/helloworld")
 public ModelAndView hello() {
 
  String helloWorldMessage = "Hello world from java2blog!";
  return new ModelAndView("hello", "message", helloWorldMessage);
 }
}

As  request first goes to dispatcherServlet and it redirects to controller class. Here @Controller depicts that this is our controller class. @RequestMapper is used to map incoming http request to handler method(hello() in above controller).So hello() method of HelloWorldController.java will handle GET request from dispatcher.So when we have url of
http://localhost:8080/SpringMVCHelloWorldExample/helloworld or
http://localhost:8080/SpringMVCHelloWorldExample/helloworld.html
above method will get called.

As you can see ModelAndView object is being returned in hello() method. It will call below constructor of ModelAndView class.
ModelAndView(String viewName, String modelName, Object modelObject)
Below diagram will make it clear

8) Modify index.jsp as below
<%@ 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>HelloWorld</title>
</head>
<body>
<a href="helloworld.html">Click here to read hello message </a>
</body>
</html>
Create hello.jsp in /WEB-INF/ folder
<%@ 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>Hello</title>
</head>
<body>
${message}
</body>
</html>

Configuring spring mvc application 

 9) Now we need to configure two files "web.xml" and "springmvc-dispatcher-servlet.xml" We need to declare DispatcherServlet in web.xml for spring MVC. When DisplatcherServlet is initialized,spring tries to load application context from [servlet name]-servet.xml file. So in this case, it will be try to load springmvc-dispatcher-servlet.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_3_0.xsd"
    version="3.0">
    <display-name>Archetype Created Web Application</display-name>
     <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
    <servlet>
  <servlet-name>springmvc-dispatcher</servlet-name>
  <servlet-class>
   org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
  <load-on-startup>1</load-on-startup>
 </servlet>
 
 <servlet-mapping>
  <servlet-name>springmvc-dispatcher</servlet-name>
  <url-pattern>/</url-pattern>
 </servlet-mapping> 
    </web-app>

10) create xml file named "springmvc-dispatcher-servlet.xml" in /WEB-INF folder as below.
<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="org.arpit.java2blog.springmvc.controller" />

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

</beans>
context:component-scan allows spring to load its class and child class. As you can see, we have given controller package here, so it will load HelloWorldController.class.
InternalResourceViewResolver is resource view resolver bean which will resolve view, prefix and suffix will be added to view used in ModelViewObject. As we have used "hello" as viewName in ModelAndView object. It will search for view in /WEB-INF/hello.jsp.


11) It 's time to do maven build.
Right click on project -> Run as -> Maven build
12) Provide goals as clean install (given below) and click on run


Run the application


13) Right click on project -> run as -> run on server
Select apache tomcat and click on finish

14) You will see below screen:

When you click on above link, you will get below screen

We are done with Spring MVC hello example. If you are still facing any issue, please comment.
Download
click to begin
20KB .zip

Project structure:


If you getting 404 error with above steps, you may need to follow below steps:


1) If you are getting this warning into your Tomcat startup console log, then it can cause the issue

WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.j2ee.server:SpringMVCHelloWorldExample' did not find a matching property.

This particular warning basically means that the <Context> element in Tomcat's server.xml contains an unknown attribute source and that Tomcat doesn't know what to do with this attribute and therefore will ignore it.
To resolve this in eclipse,
Remove the project from the server from the Server View. Right click on server -> add and remove

then remove project from server configuration.


Then run the project under the same server. Warning should be removed now
Or if warning still remains then

  • Go to server view
  • Double click on your tomcat server. It will open the server configuration.
  • Under server options check ‘Publish module contents to separate XML files’ checkbox. 
  • Restart your server. This time your page will come without any issues.
2) Try to update Maven project.
Right click on project ->Maven-> update project
then

This should solve you issues.

Written by Arpit:

If you have read the post and liked it. Please connect with me on Facebook | Twitter | Google Plus

 

Java tutorial for beginners Copyright © 2012