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 .:: | ||
Comments
62 Responses to “Spring MVC Hello World, Spring MVC 3.2 Hello World Example In Eclipse”
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;)
jar file missing bro will check jar file again redeploy …
you should first explain the annotations such as @controller….,@requestmapping….
you got it right
what is the difference between comparable and comparator interfaces and give me one real time example please
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().
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 ?????
PLEASE UPDATE <property name="prefix" value="WEB-INF/views/jsp/" />.
it is worked for me!
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>
Thank you , it is really helpful.
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.
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
how to upload any pdf,image and store in MySql
Thank you so much. Really its makes me to understand the springflow very clearly. Once again thanks.
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.
Nice Explanation yar….
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’
Hi,
I see the warning : No mapping found for HTTP request with URI [/Mvc/] in DispatcherServlet with name ‘welcome’. How to overcome this ??
How DispatcherServlet knows Java4sController is the controller here in this program?
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
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.
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.
Thank you so much for this explanation , i could finally understand the flow in Spring 😀
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.
sir you tutorial is nice .I want to know the difference between spring mvc and servlet
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.
Hi ,
Could anyone please explain role of Handler Mapper here ?
Many thanks in advance
Regards,
Krupaharan M
brother every thing is fine. But I have one doubt. where the java4s.html file in “index.jsp”. Give me clarity on that.
Brother, java4s.html is a link but not a file.
sir,
can plz explain the difference between spring and spring mvc
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".
superb article.hats off.very beautifully explained.
from which file we get the namespaces in bean definition in “welcome-servlet,xml” file
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)
Add Spring web mvc jar file in lib folder
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.
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 🙂
Both web.xml and welcome-servlet.xml must be in lib folder .This will work
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.
Its Good Article
Above given program is not working on my desktop………. Plz help me….
Excellent explaniation every one can understand
Nice tutorial and well explained , please write more example in spring mvc,that would be very help to us,
Excellent Explanation
Thanks a lot
Iam getting this error can u solve????
org.springframework.beans.factory.BeanDefinitionStoreException: Unexpected exception parsing XML document from ServletContext resource
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
This example is not up to the mark.
Really it is very helpful for the begineers….thank you….
It is printing
${welcomeMessage} on welcomePage.jsp but not printing the value of ${welcomeMessage}.
why it is so?
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.
it is very useful for understanding for flow of spring famework once again thanks.
Really super explanation …. Thank you so much
awesome .u make it easy
Superb explanation..
$upb !!!Working fine.
Please describe: how DispatcherServlet finds Java4Controller class? you are not mapping anywhere controller class in any xml so how!!!
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.
Very Nicely explained..
could you please guide me how to use ajax in springmvc curd operations..
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.
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.
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.
Hello while creating project how to decide which version to use for jar files?
Can someone explain which file here acting as Dispatcher servlet ? Which class or file is acting as Handler mapper ?