You are on page 1of 4

Spring MVC Development Quick Tutorial | Java Code Geeks

http://www.javacodegeeks.com/2011/02/spring-mvc-development-tutor...

Home

Software

Resources

Tutorials

Examples

Job Board

Join Us

About

RSS

Email

Follow us

Become a fan

LinkedIn

G+

Java

Android

JVM Languages
Enterprise Java

Software Development

Agile

DevOps

Communications

Career

Misc

Meta JCG

Search this site...


April 30, 2013 7:36 pm

You are here: Home

Spring MVC Development Quick Tutorial

About Jakub Holy


Jakub is an experienced Java[EE] developer working for a lean & agile consultancy in Norway. He is interested in code quality, developer productivity, testing, and in how to make projects succeed.

Spring MVC Development Quick Tutorial


by Jakub Holy on February 12th, 2011 | Filed in: Enterprise Java Tags: Spring, Spring MVC

This is a short tutorial on Developing web applications with Spring from Manoj at The Khangaonkar Report, one of our JCG partners. (NOTE: The original post has been slightly edited to improve readability) Spring MVC enables easy web application development with a framework based on the Model View Controller architecture (MVC) pattern. The MVC architectural pattern requires the separation of the user interface (View), the data being processed (Model) and the Controller which manages the interactions between the view and the model. At the core of Spring MVC is a servlet, the DispatcherServlet, that handles every request. The DispatcherServlet routes the HTTP request to a Controller class authored by the application developer. The controller class handles the request and decides which view should be displayed to the user as part of the response. Let us develop a simple web application that takes a request and sends some data back to the user. Before you proceed any further, I recommend you download the source code from here. For this tutorial you will also need: 1. A servlet container like Tomcat 2. Spring 3.0 3. Eclipse is optional. I use eclipse as my IDE. Eclipse lets you export the war that can be deployed to Tomcat. But you can use other IDEs or command line tools as well. 4. Some familiarity with JSPs and Servlets is required. Step 1: If you were to develop a web application in J2EE, typically you do it by developing servlets and/or JSPs, that are packaged in a .war file. Also necessary is a deployment descriptor web.xml that contains configuration metadata. The war is deployed to an application server like Tomcat. With Spring, the first thing to do is to wire Spring to this J2EE web infrastructure by defining org.springframework.web.servlet.DispatcherServlet as the servlet class for this application. You also need to define org.springframework.web.context.ContextLoaderListener as a listener. ContextLoaderListener is responsible for loading the spring specific application context which has Spring metadata. The web.xml setup ensures that every request to the application is routed by the servlet engine to DipatcherServlet. The updated to web.xml is shown below: 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </ listener-class > </listener > <servlet> <servlet-name >springmvc</servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet </ servlet-class> <load-on-startup >1</load-on-startup> </servlet> <servlet-mapping> <servlet-name >springmvc</servlet-name> <url-pattern>*.htm</url-pattern> </servlet-mapping >

Join Us

With 356,145 Mar unique visitors we are placed among the top authority Java related sites around. Constantly being on the lookout for partners that are interested in contributing towards the creation of the best online Java developers community we encourage you to join us. So If you have a blog with unique and interesting content then you should check out our JCG partners program. You can also be a guest writer for Java Code Geeks and hone your writing skills in addition to utilizing our revenue sharing model to monetize your technical writing!
Carrer Opportunities

Java Developer CheapCaribbean.com Plano, TX ( FULL-TIME ) April 22nd, 2013 Java Developer ENCLIPSE Indian Head, MD ( FULL-TIME ) April 21st, 2013 Java Developers Sogeti New York, NY ( FULL-TIME ) April 20th, 2013 Java Developer Deloitte Tallahassee, FL ( FULL-TIME ) April 20th, 2013 JAVA Developer Varen Technologies Fort Meade, MD ( FULL-TIME ) April 20th, 2013
Tags
Akka Android Tutorial Apache Camel Apache Hadoop

Apache Maven Apache Tomcat


Books Cloud

Big Data

Concurrency
EJB

Design Patterns Eclipse


JavaOne JAXB JBoss

Google Guava

Step 2: The heavy lifting in this web application is done by a controller class. This is an ordinary java class or bean that extends org.springframework.web.servlet.mvc.AbstractController. We override the handleRequestInternal method. In this method, you would do the things necessary to handle the request which may include for example reading from a database. The method returns a org.springframework.web.servlet.ModelAndView object which encapsulates the name of the view and any data (model) that needs to be displayed by the view. ModelAndView holds data as name value pairs.This data is later made available to the view. If the view is a jsp, then you can access the data using either jstl techniques or by directly querying the Request object. The code for our controller is shown below: 1 2 3 4 5 6 7 8 public class SpringMVCController extends AbstractController { protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) { ModelAndView mview = new ModelAndView("springmvc") ; mview.addObject("greeting", "Greetings from SpringMVC") ; mview.addObject("member1", new Member("Jonh","Doe", "1234 Main St","Pleasanton","94588","kh@gmail.com","1234")) ; return mview ; }

Google GWT Java 7 Java 8 Java EE6

JavaFX

JBoss Hibernate JMS JPA JSF JSON JUnit JVM Logging


MongoDB NoSQL Oracle GlassFish
Performance and Scalability

MapReduce

Performance

Play Framework Project Management

RESTful Web Services Security

Spring

Spring MVC
XML

Spring Security

Testing

1 de 4

30/04/2013 12:47

Spring MVC Development Quick Tutorial | Java Code Geeks

http://www.javacodegeeks.com/2011/02/spring-mvc-development-tutor...

The name of the view springmvc is passed in to the constructor of ModelAndView. The addObject method invocations add 2 model objects, greeting and member1. Later you will see how the view can retrieve the objects and display them. Step 3: Every Spring application needs metadata that defines the beans and their dependencies. For this application, we create a springmvc-servlet.xml. We help spring find it by specifying its location in web.xml. 1 2 3 4 <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/springmvc-servlet.xml</param-value> </context-param>

In springmvc-servlet.xml, the controller bean is defined as: 1 <bean name="/*.htm" class="com.mj.spring.mvc.SpringMVCController"/>

Step 4: How does DispatcherServlet know which Controller should handle the request? Spring uses handler mappings to associate controllers with requests. 2 commonly used handler mappings are BeanNameUrlHandlerMapping and SimpleUrlHandlerMapping. In BeanNameUrlHandlerMapping, when the request url matches the name of the bean, the class in the bean definition is the controller that will handle the request. In our example, we use BeanNameUrlHandlerMapping as shown below. Every request url ending in .htm is handled by SpringMVCController. 1 <bean name="/*.htm" class="com.mj.spring.mvc.SpringMVCController"/>

In SimpleUrlHandlerMapping, the mapping is more explicit. You can specify a number of URLs and each URL can be explicitly associated with a controller. Step 5: How does the DispatcherServlet know what to return as the response ? As mentioned earlier, the handleRequestInternal method of the controller returns a ModelAndView Object. In the controller code shown above, the name of the view springmvc is passed in the constructor of ModelAndView. At this point we have just given the name of the view. We have not said what file or classes or artifacts help produce the html, nor have we said whether the view technology used is JSP or velocity templates or XSLT. For this you need a ViewResolver, which provides that mapping between view name and a concrete view. Spring lets you produce a concrete view using many different technologies, but for this example we shall use JSP. Spring provides a class InternalResourceViewResolver that supports JSPs and the declaration below in springmvc-servlet.xml tells spring that we use this resolver. The prefix and suffix get added to view name to produce the path to the jsp file that renders the view. 1 2 3 4 <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/"></property> <property name="suffix" value=".jsp"></property > </bean >

Step 6: In this example, the view resolves to springmvc.jsp, which uses JSTL to get the data and display it. Spring makes the model objects greeting and member1 available to the JSP as request scope objects. For educational purposes, the code below also gets the objects directly from the request. 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 // Using JSTL to get the model data ${greeting} ${member1.lastname // Using java to get the model directly from the request Map props = request.getParameterMap() ; System.out.println("PARAMS =" + props) ; Enumeration em = request.getAttributeNames() ; while (em.hasMoreElements()) { String name = (String) em.nextElement() ; System.out.println("name = "+name) ; } System.out.println("Attrs are "+request.getAttributeNames()) ; System.out.println("greeting is "+ request.getAttribute("greeting")) ; Member m = (Member)request.getAttribute("member1") ; System.out.println("member is "+m.toString()) ;

Step 7: All files we have developed so far should be packaged into a war file as you would in any web application. The war may be deployed to tomcat by copying to tomcat_install\webapps. I built a war that you can download here. Step 8: Point your web browser http://localhost:8080/springmvc/test.htm to run the application. The browser should display the data.

To summarize, Spring simplifies web application development by providing building blocks that you can assemble easily. We built a web application using Spring MVC. Spring provides an easy way to wire together our model, the controller SpringMVCController and the view springmvc.jsp. We did not have to explicitly code any request/response handling logic. By changing the metadata in springmvc-servlet.xml, you can switch to a different controller or a different view technology. Thats it guys, a simple guide to Developing web applications with Spring by our JCG partner Manoj Khangaonkar. You can find the source

2 de 4

30/04/2013 12:47

Spring MVC Development Quick Tutorial | Java Code Geeks

http://www.javacodegeeks.com/2011/02/spring-mvc-development-tutor...

code created for this tutorial here. Dont forget to share! Related Articles: JBoss 4.2.x Spring 3 JPA Hibernate Tutorial Exposing a POJO as a JMX MBean with Spring Spring 3 RESTful Web Services JAXWS with Spring and Maven Tutorial Securing GWT apps with Spring Security Aspect Oriented Programming with Spring AspectJ and Maven Related Snippets : Spring MVC interceptor example Declare bean in Spring container Sending e-mails with Spring

You might also like: Spring MVC Session Tutorial Spring MVC for Atom Feeds SpringMVC 3 Tiles 2.2.2 Integration Tutorial Tutorial: Hibernate, JPA & Spring MVC Part 2 Spring MVC: Creation of a simple Controller with Java based config

Share and enjoy!

6 comments

Best

Community

Share

Nandu

Thank you very much for your valuable tutorial.. this helped me alot...

scooby

That's great, but you seemed to miss a bit. How do you then get the information that you have set in the model back out of the model when the next request is made controller in the flow? Your example seems to asume a 1 to 1 to 1 relationship between a model, view and controller. There needs to be away of mapping multiple views to a controller. Consider a registration process over several pages or placing an order in a shopping cart. Multiple views need to feed the same model.

Luka otar

this is an excellent 'quick and dirty' tutorial, thank you

Navya

when doing switching between two view and one controller in MVC using gwt ..iam using concept deferred binding...but am not able get it ..how to do.. plz help me out .. using GWT 2.3 and GXT 2.24

Harshit

other useful link with annotations i found Spring mvc annotations

papirrin

Good tutorial. Thanks!

ALSO ON JAVA CODE GEEKS

AROUND THE WEB 3 comments

What's this?

When Maven Dependency Plugin Lies

Why a synchronized StringBuffer was never a good idea 2 comments Simulation of time consuming actions in integration tests 1 comment Advantages and Disadvantages of Cloud Computing Cloud computing pros and cons

85-year-old bachelorette is looking for love: Watch Burning Love now Yahoo Secret to a Gorgeous Face: It's the Eyebrows
eHow Style

Innovative Ways To Get Your Finances In Order In 2012 Investopedia The Worst Home Selling Mistake
About.com

3 de 4

30/04/2013 12:47

Spring MVC Development Quick Tutorial | Java Code Geeks

http://www.javacodegeeks.com/2011/02/spring-mvc-development-tutor...

Knowledge Base

Partners

Hall Of Fame

About Java Code Geeks

Examples Resources Software Tutorials

Mkyong

Android Full Application Tutorial series GWT 2 Spring 3 JPA 2 Hibernate 3.5 Tutorial

JCGs (Java Code Geeks) is an independent online community focused on creating the ultimate Java to Java developers resource center; targeted at the technical architect, technical team lead (senior developer), project manager and junior developers alike. JCGs serve the Java, SOA, Agile and Telecom communities with daily news written by domain experts, articles, tutorials, reviews, announcements, code snippets and open source projects.

The Code Geeks Network

Android Game Development Tutorials Android Google Maps Tutorial Android Location Based Services Application GPS location Funny Source Code Comments Java Best Practices Vector vs ArrayList vs HashSet Android JSON Parsing with Gson Tutorial Android Quick Preferences Tutorial

Java Code Geeks .NET Code Geeks Web Code Geeks

License

Java Code Geeks content is offered under Creative Commons Attribution-ShareAlike 3.0 Unported License. License For any reuse or distribution, you must make clear to others the license terms of this work. The best way to do this is with a link to this web page. Any of the above conditions can be waived if you get written permission from Java Code Geeks. Nothing in this license impairs or restricts the author's moral rights.

2010-2012 Java Code Geeks. Licenced under a Creative Commons Attribution-ShareAlike 3.0 Unported License. All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners. Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries. Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

4 de 4

30/04/2013 12:47

You might also like