You are on page 1of 5

Hello World Example using Spring MVC Framework

Hi all, in this article i ll show u how to write a simple Spring MVC application printing 'Hello World' after we submit a form. ok lets have a look over the directory structure that i used to build the application

build : This directory includes build.properties file. src :This includes all the java files. web :This includes all .xml and .jar files. build/build.properties src.dir=src dist.dir=dist web.dir=web lib.dir=${web.dir}/WEB-INF/lib classes.dir=${dist.dir}/WEB-INF/classes app.name=springmvc war.dir=war tomcat.home=C:/esi/apps/apache-tomcat-5.5.26 tomcat.webapps=${tomcat.home}/webapps tomcat.work=${tomcat.home}/work/Standalone/localhost Please be sure to change the path for Tomcat home and its webapps directory if u installed some where else. build.xml <?xml version="1.0"?> <project name="StrutsSpringHibernateProject" basedir="." default="install"> <!-- Import properties file into this Build File --> <property file="build\build.properties"/> <!-- Set the ClassPath which is used for Compiling and Running the application --> <path id="classpath"> <fileset dir="${lib.dir}" includes="*.jar"/> </path> <!-- Delete the destination Directory and War directory before Building the application --> <target name="clean"> <delete dir="${dist.dir}"/> <delete dir="${war.dir}"/> </target> <!-- Copy all the resources that are necessary for running the application --> <target name="copy-resources"> <mkdir dir="${dist.dir}"/> <mkdir dir="${war.dir} "/> <copy todir="${dist.dir}"> <fileset dir="${web.dir}"> <exclude name="**/*.java"/> </fileset> </copy> <copy todir="${classes.dir}"> <fileset dir="${src.dir}"> <exclude name="**/*.java"/> </fileset> </copy> <mkdir dir="${classes.dir}"/>

</target> <!-- Compile the source files --> <target name="compile" depends="clean,copy-resources"> <javac srcdir="${src.dir}" destdir="${classes.dir}" includes="**/*.java" classpathref="classpath" /> </target> <!-- create a war file for the application --> <target name="war" depends="compile"> <jar jarfile="${war.dir}/${app.name}.war" basedir="${dist.dir}"/> </target> <!-- Tomcat Related Targets --> <!-- Clean the appliaction directory in webapps --> <target name="tomcat-clean"> <delete dir="${tomcat.webapps}/${app.name}"/> <delete dir="${tomcat.work}/${app.name}"/> </target> <!-- copy the war file created into tomcat webapps directory --> <target name="install" depends="war,tomcat-clean"> <copy file="${war.dir}/${app.name}.war" tofile="${tomcat.webapps}/${app.name}.war" /> </target> </project> As you can see the build.xml file, there are different targets defined to build the application like clean,compile,copy-resources,tomcat-clean and install.Each has its specific task to do and depends on others. just build it with ant and it will do all the work for you. ok now lets have a look over the things under web directory

WEB-INF : This directory holds all the tlds,*.jar files and *.xml files index.jsp : The jsp page which asks for user details. success.jsp : When the application runs file we will be forwarded to this.We print 'Hello World' in this .jsp ok now lets have a look over all these jsp pages index.jsp <html> <head> <title>Spring MVC Example</title> </head> <body> <form action="submitAction.htm"> <h3>Spring MVC Example Application.</h3> <br><br> <b>Please click on the button below to see the Hello World message</b> <br> <input type="submit" value="Click Here > > >"> </form> </body> </html> Have a look over action attribute in form tag, its specified to 'submitAction.htm' this is specified in hello-servlet.xml file.

success.jsp <html> <head> <title>SpringMVC Framework Implementation</title> </head> <body> <h2><%=request.getAttribute("message") %></h2> </body> </html> The message attribute is set in the controller class . ok now lets have a look over the WEB-INF directory

lib : This directory holds all the jar files that are necessary for running this application.Just copy the spring.jar,commons-logging.jar and servlet.jar files into this lib directory. Now lets have a look over all these xml files that are required to configure the application web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app> <servlet> <servlet-name>hello</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>*.htm</url-pattern> </servlet-mapping> <servlet> <servlet-name>context</servlet-name> <servlet-class>org.springframework.web.context.ContextLoaderServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> </web-app> The servlet specified here is DispatcherServlet, the same as ActionServlet we use for Struts. Hava a look over the servlet name, the sping config xml files must start with hello as like this 'helloservlet. xml' . hello-servlet.xml <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springsource.org/dtd/spring-beans.dtd"> <beans> <bean name="/submitAction.htm" class="com.springmvc.action.HelloController"> <property name="greeting"> <value>Hello World</value> </property> </bean> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="suffix"> <value>.jsp</value>

</property> </bean> </beans> This xml file specifies the bean which should be invoked for the action passed from index.jsp. Here we are setting the greeting property with 'Hello World', this is the message that will be viewed on success.jsp page . The view resolver bean specifies the mapping details for the passed reference from the controller. When used InternalResourceViewResolver class it check for the files with the name that matches when returning the ModelAndView object. This also includes which type of files to check out, Here we specified to check over all *.jsp files matching the parameter that is passed from the controller. applicationContext.xml <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springsource.org/dtd/spring-beans.dtd"> <beans> </beans> as we are not writing any service logic beans this can be kept empty. The only class we specified here is HelloController in the src directory with package 'com.springmvc.action' .

HelloController.java package com.springmvc.action; import javax.servlet.http.*; import org.springframework.web.servlet.mvc.*; import org.springframework.web.servlet.*; public class HelloController implements Controller{ public ModelAndView handleRequest(HttpServletRequest request,HttpServletResponse response) throws Exception{ return new ModelAndView("success","message",greeting); } private String greeting; public void setGreeting(String greeting){ this.greeting = greeting; } } This class implements the main Interface Controller, which is Spring's MVC main Interface . The ModelAndView class is the one which is used to bind model and view . The object passed would be including the mapping path for the view, and the greeting variable is binded with 'messages' attribute. This attribute is set into the request object.

So thats it, now u have all the java code stuff, all the .xml files and .jsp files. just build ur application using ant. You can see two directorys created 'dist' and 'war' as shown below

Now just restart your tomcat and type the url ' http://localhost:8080/springmvc/ ' you should be able to see the screen as such if the application runs fine..

and when submitted the form on click the button, we get should see the 'Hello World' as such in success.jsp

Just have a look over the java code and xml files after running the application. Detailed explanation is not given here as this is just a basic application and can be understood by the ones who had an overview of all Struts MVC Framework. Ok thats all with this example. I just did this one in order to have a pratice over all of this framework. If at all you get any errors, just copy the exception thrown and search in google, I tried the same way and atlast i got the result. If all the JAR files are placed properly you wouldnt get any error. ok thnx folks for reading my post, Regards, Rohit Tayal tayalr@gmail.com