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.

Was this post helpful?

Comments

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

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

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

  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 *