Newsletter

Spring MVC Hello World, Spring MVC 3.2 Hello World Example In Eclipse

Spring-MVC » on Jul 14, 2013 { 62 Comments } By Sivateja

Let us execute spring MVC hello world application with complete explanation, will see it in an eclipse 🙂

Open eclipse > File  > Dynamic Web Project

Give Project Name > Finish

Directory Structure

Required Files

  • Java4sController.java
  • welcomePage.jsp
  • web.xml
  • welcome-servlet.xml
  • index.jsp

index.jsp

<html>
<head>
<title>Java4s.com Spring MVC 3.x</title>
</head>
<body>

<font size="2px" face="verdana">
  Welcome...
   <a href="java4s.html"><br> Click here to check the output :-)</a>
</font>

</body>
</html>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" id="WebApp_ID" version="2.4">
<servlet>
  <servlet-name>welcome</servlet-name>
     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
     <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
     <servlet-name>welcome</servlet-name>
     <url-pattern>/</url-pattern>
  </servlet-mapping>

  <welcome-file-list>
     <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

Java4sController.java

package java4s;

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

@Controller
public class Java4sController {

@RequestMapping("/java4s")
public ModelAndView helloWorld() {

   String message =  "Welcome to Java4s.com Spring MVC 3.2.x Sessions";
   message += "<br>You Did it....!";

   return new ModelAndView("welcomePage", "welcomeMessage", message);
}//ModelAndView closed

}

welcome-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
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">

<context:component-scan base-package="java4s" />

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/jsp/" />
<property name="suffix" value=".jsp" />
</bean>

</beans>

welcomePage.jsp

<html>
<body>
  <font face="verdana" size="2">
     ${welcomeMessage}
  </font>
</body>
</html>

Execution Flow

  • Run the application, then index.jsp file will be executed > click on the link given (I have given <a href=”java4s.html”>Click here to check the output :-)</a>)
  • Once you click on that link, container will check the URL pattern at web.xml and passes the request to the DispatcherServlet
  • DispatcherServlet then passes that request to our controller class
  • Actually we are passing java4s.html from index.jsp right ? so DispatcherServlet verifies this ‘java4s’ name with the string in @RequestMapping(“-“) in our controller class if same it will executes the following method, which gives ModelAndView object as return type

In our controller class we are returning…

return new ModelAndView("welcomePage", "welcomeMessage", message);

Means first argument is ‘View’ page name [ Where we are sending our result ], second, third arguments are key,values

  • So DispatcherServlet search for the name welcomePage in /jsp folder with extension .jsp [ you can change the ‘view page’ folder name/location and its extension in welcome-servlet.xml at line numbers 14,15],  once the file was opened you can access the data by using the key welcomeMessage [2nd parameter in ModelAndView object]
  • Check welcomePage.jsp > i am printing the result by calling the key ${welcomeMessage}

Note

  • In web.xml we have given servlet name as welcome, so spring configuration file name must be welcome-servlet.xml [ {servletName-in-web.xml}-servlet.xml ]

Output

​ ​​

You Might Also Like

  ::. About the Author .::

Java4s_Author
Sivateja Kandula - Java/J2EE Full Stack Developer
Founder of Java4s - Get It Yourself, A popular Java/J2EE Programming Blog, Love Java and UI frameworks.
You can sign-up for the Email Newsletter for your daily dose of Java tutorials.

Comments

62 Responses to “Spring MVC Hello World, Spring MVC 3.2 Hello World Example In Eclipse”
  1. ramana says:

    i am trying to execute Spring MVC Hello World program in Dynamic web project using eclipise it is rising java.lang.NoSuchMethodError: org.springframework.core.io.ResourceEditor.(Lorg/springframework/core/io/ResourceLoader;Lorg/springframework/core/env/PropertyResolver;)

  2. GSolanki says:

    you should first explain the annotations such as @controller….,@requestmapping….
    you got it right

  3. B.Prasad says:

    what is the difference between comparable and comparator interfaces and give me one real time example please

    • Ajit says:

      comparable used for default natural sorting order where as comparator use for customized sorting order.
      comparable contain only one method compareTo() where as comparator contain two method compare() and equals().

  4. HI ,
    I am sending the request from index.jsp as only java4s, but request is not happening,Could You please suggest me, why it is not happening ?????

    • teju says:

      PLEASE UPDATE <property name="prefix" value="WEB-INF/views/jsp/" />.
      it is worked for me!

    • Prashanth B says:

      please check in <url-pattern>, extension should must be same.
      eg: 1.if u give request as "java4s" make your <url-pattern>/</url-pattern>

      2.if u give request as "java4s.htm" make your <url-pattern>*.htm</url-pattern>

  5. Prasanth says:

    Thank you , it is really helpful.

  6. In index.html, you have given “java4s.html” as href, but in controller class, you have given “/java4s” as parameter in @RequestMapping.
    You haven’t explain about how this is working.
    Please explain the same.

    Thanks.

  7. Hi,

    Please add missing spring-aop-x.x.x.RELEASE.jar into WEB-INF\web folder. This will help you to run the above program without errors.

    Thanks
    Deepak Kumar

  8. prashant says:

    how to upload any pdf,image and store in MySql

  9. Loganathan says:

    Thank you so much. Really its makes me to understand the springflow very clearly. Once again thanks.

  10. Hi, Earlier I ran this example successfully. But now I am getting 404 error after clicking on a href link. Can u plz suggest.

    please note- I am just trying the example given above. I didn’t do any changes.

  11. Sachin says:

    Nice Explanation yar….

  12. hari krishna says:

    When i ran this example i am getting the below exception . Please assist.

    No mapping found for HTTP request with URI [/Spring_MVC/java4s.html] in DispatcherServlet with name ‘welcome’

  13. Dushyanth says:

    Hi,

    I see the warning : No mapping found for HTTP request with URI [/Mvc/] in DispatcherServlet with name ‘welcome’. How to overcome this ??

  14. How DispatcherServlet knows Java4sController is the controller here in this program?

  15. Rishabh Chaturvedi says:

    Dear Sebin+Joseph,

    The same doubt I was having but according to me the ans is below->

    In Java4sController.java line no -7(@Controller annotation used).
    This @Controller annotation indicates that a particular class serves the role of a controller and this is How DispatcherServlet knows about the controller class.
    All,Please correct me if I am wrong

    Regards,
    Rishabh

  16. Rishabh+Chaturvedi says:

    Hey Sebin+joseph..

    According to me DispatcherServlet knows about the controller by @Controller Annotation which is used in line no 7 in Java4sController.java.
    This Annotation tells the DispatcherServlet about the particular class that will work as a Controller.

  17. Venkata Ramireddy CH says:

    I followed as it is given in your example. But after running my application, it is not reaching controller class. I am not seeing any error message in console. Infact it is showing 404 error message on click on the link.

  18. Malek says:

    Thank you so much for this explanation , i could finally understand the flow in Spring 😀

  19. kiran kumar reddy says:

    I followed as it is given in your example. But after running my application, it is not reaching controller class. I am not seeing any error message in console. Infact it is showing 404 error message on click on the link.

    please help on this.
    thanks in advanse.

  20. sarvesh says:

    sir you tutorial is nice .I want to know the difference between spring mvc and servlet

  21. savita says:

    I followed as it is given in your example. But after running my application, it is not reaching controller class. I am not seeing any error message in console. Infact it is showing 404 error message on click on the link.

    please help on this.
    thanks in advanse.

  22. krupaharan says:

    Hi ,

    Could anyone please explain role of Handler Mapper here ?

    Many thanks in advance

    Regards,
    Krupaharan M

  23. siva says:

    brother every thing is fine. But I have one doubt. where the java4s.html file in “index.jsp”. Give me clarity on that.

  24. saranya says:

    sir,

    can plz explain the difference between spring and spring mvc

    • Danalakota Santhosh says:

      Spring is a framework.

      Spring MVC (Model view controller) Spring Web MVC is the original web framework built on the Servlet API and included in the Spring Framework from the very beginning. The formal name "Spring Web MVC" comes from the name of its source module spring-webmvc but it is more commonly known as "Spring MVC".

  25. nitin says:

    superb article.hats off.very beautifully explained.

  26. maheswari says:

    from which file we get the namespaces in bean definition in “welcome-servlet,xml” file

  27. maheswari says:

    Hi,
    Can u please tell me the reason why i’m getting this error.

    Allocate exception for servlet spring
    java.lang.ClassNotFoundException: org.springframework.web.servlet.DispatcherServlet
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1714)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1559)
    at org.apache.catalina.core.DefaultInstanceManager.loadClass(DefaultInstanceManager.java:532)
    at org.apache.catalina.core.DefaultInstanceManager.loadClassMaybePrivileged(DefaultInstanceManager.java:514)
    at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:133)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1137)
    at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:858)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:136)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:744)

  28. Amar says:

    Dear

    I followed as it is given in your example. But after running my application, it is not reaching controller class. I am not seeing any error message in console. Infact it is showing 404 error message on click on the link.

    • seetaram says:

      Dear

      in welcome-servlet.xml we have a base-package="give the complete package name">

      for ex: in this example package name is "java4s" hence it was given as follows
      <context:component-scan base-package="java4s" />

      Hope you got the point 🙂

  29. vikram kumar says:

    hi sivateja, thanks for giving nice explanation, kindly provide me sample project using spring and hibernate annoatation based application for login application, it would great helpful for me.

  30. siva says:

    Its Good Article

  31. Shaggy says:

    Above given program is not working on my desktop………. Plz help me….

  32. Excellent explaniation every one can understand

  33. Krishna says:

    Nice tutorial and well explained , please write more example in spring mvc,that would be very help to us,

  34. kiruthi says:

    Excellent Explanation

  35. ravi says:

    Thanks a lot

  36. naresh says:

    Iam getting this error can u solve????

    org.springframework.beans.factory.BeanDefinitionStoreException: Unexpected exception parsing XML document from ServletContext resource

  37. Sameer says:

    java4s.html file is not present in above code so Its generate the HTTP Status 404 – /SpringMVC/WEB-INF/jsp/welcomePage.jsp error….. plz tell me a valid code

  38. Rajasekhar says:

    This example is not up to the mark.

  39. Pallavireddy says:

    Really it is very helpful for the begineers….thank you….

  40. Lalchand says:

    It is printing
    ${welcomeMessage} on welcomePage.jsp but not printing the value of ${welcomeMessage}.

    why it is so?

    • srinivas says:

      in jsp page by default isELIgnored="true".so,it will not show the stored value in message. add isELIgnored="false" to your jsp page and try.

  41. it is very useful for understanding for flow of spring famework once again thanks.

  42. Raghu Adapa says:

    Really super explanation …. Thank you so much

  43. Nitin says:

    awesome .u make it easy

  44. Haider says:

    Superb explanation..

  45. Narendra says:

    $upb !!!Working fine.
    Please describe: how DispatcherServlet finds Java4Controller class? you are not mapping anywhere controller class in any xml so how!!!

    • namasivayam G says:

      Narendra,

      The welcome-servlet specifies the base package name, the dispatcher servlet will scan the base package and identifies the Annotated(@controller) and find the controller.

  46. vikas says:

    Very Nicely explained..

    could you please guide me how to use ajax in springmvc curd operations..

  47. Manash Ranjan says:

    Sir,your teaching is good but while i developing time i am getting 404 error code i checked but every thing is on write place but still i am getting same please give me some solution about this.

  48. Navin says:

    Message is not passed from from controller to view. what could be the issue? ${(1+2)*3} evaluates correctly. so its not issue of jsp tag. i think the message is not transferred.

  49. Azhar says:

    after clicking on href, getting below
    HTTP Status 404 –
    type Status report
    message
    description The requested resource is not available.
    Apache Tomcat/7.0.82

    Any help would be appreciated.

  50. Meenal says:

    Hello while creating project how to decide which version to use for jar files?

  51. sushant jain says:

    Can someone explain which file here acting as Dispatcher servlet ? Which class or file is acting as Handler mapper ?

Name*
Mail*
Website



By posting your answer, you agree to our comments policy.
Most Recent Posts from Top Categories
Spring Boot Hibernate Spring
Contact | About Us | Privacy Policy | Advertise With Us

© 2010 - 2024 Java4s - Get It Yourself.
The content is copyrighted to Sivateja Kandula and may not be reproduced on other websites.