Spring MVC hello world example

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

Spring MVC tutorial:

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

Create Controller  and view

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

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

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

Create hello.jsp in /WEB-INF/ folder

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.

10) create xml file named “springmvc-dispatcher-servlet.xml” in /WEB-INF folder as below.

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 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.


import_contacts

You may also like:

Related Posts

  • 10 July

    Spring MVC tutorial

    In this post, we will learn about Spring MVC tutorial. Spring MVC framework is a robust Model view controller framework which helps us to develop a loosely coupled web application. It separates different aspects of web applications with the help of MVC architecture. Model: Model carries application data. It generally includes POJO in the form […]

  • 13 September

    Spring MVC + Spring Data + Hibernate + MySQL example

    In this post, we are going to see integration of Spring MVC,Spring Data,hibernate and mysql CRUD example. We have already seen Spring MVC, hibernate and mysql example in previous tutorial. Spring Data JPA provides CRUD API, so you don’t have to write boiler plate code. You just need to create repository interface and spring will provide […]

  • 26 August

    Spring MVC Exceptional Handling using @ControllerAdvice example

    In this post , we will see how to do exceptional handling in Spring MVC using @ControllerAdvice. In previous post, we have already seen how to use @ExceptionHandler to handle exceptions but @ExceptionHandler can be applied to one controller only but what if you want to handle exception globally i.e. across multiple controller. You can use @ControllerAdvice to handle […]

  • 26 August

    Spring MVC Exceptional Handling using @ExceptionHandler example

    In this post , we will see how to do exceptional handling in Spring MVC using @ExceptionalHandler. You can use @ExceptionHandler to redirect to error view when exception occurs. Lets understand this with the help of example: Source code: Download click to begin 20KB .zip 1) Create a dynamic web project using maven in eclipse named “SpringMVCExceptionalHandlerExample” Maven dependencies 2) Our […]

  • 25 August

    Spring MVC Hibernate MySQL CRUD example

    In this post, we are going to see integration of Spring MVC, hibernate and mysql CRUD example. We have already seen integration of Spring Rest with hibernate in previous tutorial. Spring MVC Tutorial Spring MVC hello world example Spring MVC Hibernate MySQL example Spring MVC Spring Data example Spring MVC Interceptor example Spring MVC angularjs […]

  • 23 August

    Spring MVC + log4j example

    In this post, we will see how to integrate Spring MVC with log4j. 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 […]

Comments

  1. The mapping doesn't seem to be working for me.

    <?xml version=”1.0″ encoding=”ISO-8859-1″?>
    <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/sprinhttp://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/sprhttp://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-
    <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>

    @Controller
    public class HelloWorldController
    {
    private static final Log s_log = LogFactory.getLog(HelloWorldController.class);

    @RequestMapping(“/helloworld”)
    public ModelAndView hello()
    {
    s_log.debug(“Entering HelloWorldController.hello()”);
    String helloWorldMessage = “Hello world from java2blog!”;
    return new ModelAndView(“hello”, “message”, helloWorldMessage);
    }
    }

    I get a 404 error when I click on the link.

    Also, I don't have a WebContent folder. I have a webapp folder. It was created by Eclipse using the maven-archetype-webapp. I'm using Tomcat 8 and Java 8.

    1. In springmvc-dispatcher-servlet.xml line 7 remember to change the base-package name to your controller package name.

  2. Hi billsd,
    As you had mentioned, 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 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.

    Please let me know if above solution solved your issue. I have updated article too.

    1. I actually did a lot of Googling yesterday and found out that that message is irrelevant. It's caused by Eclipse. Eclipse inserts a source attribute into the Context element to keep track of which app is associated with which project. The source attribute is undefined in JEE for the Context element so Tomcat prints a warning but otherwise ignores it. It's harmless. If I ran it on the sever outside of Eclipse and removed that attribute, it would work without giving that warning. Inside Eclipse, it needs to be there.

      Try running deploying yours and look at your logs. You probably get that warning too and didn't notice it.

      1. Hi bill,
        I have added source code also now at the end of post. I have just tested it and it works fine.
        Please import the project as maven project and try to run it.
        Hope this helps.

        Thanks for following this post

        1. It turned out I had some other problems with my eclipse stuff. I fixed those and now I get this:

          org.apache.catalina.core.ApplicationContext log INFO: No Spring WebApplicationInitializer types detected on classpath
          org.apache.catalina.core.ApplicationContext log INFO: Initializing Spring FrameworkServlet 'springmvc-dispatcher'
          org.springframework.web.servlet.DispatcherServlet initServletBean INFO: FrameworkServlet 'springmvc-dispatcher': initialization started
          org.springframework.web.context.support.XmlWebApplicationContext prepareRefresh INFO: Refreshing WebApplicationContext for namespace 'springmvc-dispatcher-servlet': startup date [Sun Sep 13 10:49:17 PDT 2015]; root of context hierarchy
          org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions INFO: Loading XML bean definitions from ServletContext resource [/WEB-INF/springmvc-dispatcher-servlet.xml]
          org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter initControllerAdviceCache INFO: Looking for @ControllerAdvice: WebApplicationContext for namespace 'springmvc-dispatcher-servlet': startup date [Sun Sep 13 10:49:17 PDT 2015]; root of context hierarchy
          org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter initControllerAdviceCache INFO: Looking for @ControllerAdvice: WebApplicationContext for namespace 'springmvc-dispatcher-servlet': startup date [Sun Sep 13 10:49:17 PDT 2015]; root of context hierarchy
          org.springframework.web.servlet.DispatcherServlet initServletBean INFO: FrameworkServlet 'springmvc-dispatcher': initialization completed in 1462 ms
          org.apache.coyote.AbstractProtocol start INFO: Starting ProtocolHandler [“http-apr-8080”]
          org.apache.coyote.AbstractProtocol start INFO: Starting ProtocolHandler [“ajp-apr-8009”]
          org.apache.catalina.startup.Catalina start INFO: Server startup in 2930 ms
          org.springframework.web.servlet.PageNotFound noHandlerFound WARNING: No mapping found for HTTP request with URI [/HelloWorld/helloworld] in DispatcherServlet with name 'springmvc-dispatcher'

  3. Hi bill,
    Could you please check if .class of contoller is generated in this folder
    /SpringMVCHelloWorldExample/target/SpringMVCHelloWorldExample/WEB-INF/classes/org/arpit/java2blog/springmvc/controller

    Just change SpringMVCHelloWorldExample with your project name.
    Also make sure you are creating controller class in
    src/main/java/org.arpit.java2blog.springmvc.controller folder.

    Let me know if it helps

  4. Amazing, I tested it following the tutorial, but I must have made some mistake and it didn't work. Then I downloaded the code and imported it , and it's worked. I'm really thankful.

Leave a Reply

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

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.