MemeStorm

Exploring the Spring Framework and Application Development

Basic Spring Web MVC Example

Posted in All by Jon on the February 10th, 2006

You want to get started with a simple web application that utilizes Spring’s web MVC framework. Here’s a simple project that provides such a start. It doesn’t use all of Spring’s features, nor even the best, but it will serve as a discussion point for future blog entries.

Background

When you’re putting together a simple web application, you need a few essentials:

  • A dispatcher servlet, which will intercept incoming requests.
  • A configuration that instructs the web container to route requests to the dispatcher servlet (ie. a servlet mapping)
  • Controllers (the C in MVC) that can perform the business logic and route to particular views (the V) perhaps conveying information models (the M).
  • A way for the dispatcher servlet to know which URLs to map to which controllers - called a url mapping
  • A way to determine, when a controller has done its job, how to get to the view - called a view resolver

The simple application here, skeleton1, doesn’t have a model at all, has a single controller (web.DispatchController), and a single view (myview.jsp)

How to do it and How it works

Download the source for the details. First, we want to use Spring’s DispatcherServlet as the entry point to our web application. You configure this simply in your web.xml:

<servlet>
<servlet-name>dispatch</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
<servlet>
<servlet-mapping>
<servlet-name>dispatch</servlet-name>
<url-pattern>/send/*</url-pattern>
</servlet-mapping>

Get it? This says: Create the servlet for me, call it dispatch, and map all incoming URLs that start with send to the dispatch servlet. So for example, a URL such as http://.../skeleton1/send/foobar would activate the dispatch servlet.

The rest of the configuration you do in a Spring web application context. Spring automatically looks for it using the name of the servlet as a hint. Since our servlet is called dispatch, it looks for a file called dispatch-servlet.xml in your WEB-INF directory. This configuration file will have three bits to it: the controller(s), the url mapping and the view resolver. First, the controller:

<bean id="dispatchController"
class="com.memestorm.web.DispatchController">
</bean>

No rocket science there. It’s simply a bean implementing the appropriate interface, which we’ll look at later.

The view resolver tells us how to render the output from a controller. Here’s the one I chose:

<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/views/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>

This uses a Spring-implemented InternalResourceViewResolver which basically maps to like-named views in the /WEB-INF/views directory, adding a .jsp. So for example, if our controller said “Please go to view myview,” then the above resolver would try to find the file myview.jsp in /WEB-INF/views. This is easy and extensible.

The final configuration is the URL mapping, which essentially tells the dispatcher servlet how to behave: Which incoming requests should it map to which controllers? We’ve chickened out:

<bean id="urlMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="/*">dispatchController</prop>
</props>
</property>
</bean>

This again uses a Spring-supplied URL mapper (isn’t it great, you don’t have to write any code) which, as you can see, maps all requests (/*) to the controller called dispatchController (which we defined above).

The last key to the puzzle is the controller itself. We know now that appropriate URLs (that are mapped to our dispatcher servlet) will be intercepted by the dispatcher servlet. It will then look at the URL, and on the basis of the URL mapper, map it to a particular controller (in this case, it maps all incoming URLs to the same controller), and to do this operationally it needs to invoke a method on the controller. Which method? Well, this particular URL mapper looks at the URL and “lops off” the start bit and uses what’s left. For example, if you went to http:.../skeleton1/send/actionName then it will try to invoke the method actionName() on dispatchController. Nothing too it. So, let’s check out the controller!

public class DispatchController extends MultiActionController {

public ModelAndView actionName(HttpServletRequest request,
HttpServletResponse response) throws Exception {
ModelAndView mav = new ModelAndView("myview");
mav.addObject("message", "Hiya");
return mav;
}
}

Pretty simple. This class implements the Spring MultiActionController (which really means we can have multiple control methods defined here), and provides a single control action method called actionName(). Check out the parameters - pretty much like a servlet which isn’t too surprising. The result is: ModelAndView. This is really a wrapper that tells Spring what the model data is (what data do you want to send to your view) and which view to actually send it to. In this case, we want to go to the view myview and send a string along too.

If you’ve been paying attention, you’ll know that our view resolver will look for myview.jsp, and yes, that’s what we have. Here’s a look at it:

Hello, you're in myview.jsp! <br />
The controller sent me some data,
here it is: <%=request.getAttribute("message") %>

Nothing too it. It prints a message, and grabs the model from the appropriately named attribute in the request.

So, if we now invoked http://../skeleton1/send/actionName our action will get invoked, which will eventually forward to this JSP page. You can extend at will, adding additional action methods for example, additional controllers if you like, and of course, additional views.

Downloading

Download the source
skeleton1.zip
and read the installation instructions. Short version: Download Spring (with dependencies, I’m using Spring 2M2), modify one property in our build file to point to the unzipped Spring distribution, run the build with ant, deploy on a web container (I use Tomcat).

Advanced

You’ll note that the code does just a little more than described above. In particular, we create an additional root application context with two beans a,b, and we make sure that we access and call these beans from the controller. Oh, and we use the logging described in Refreshable log4j configuration files.


Print This Post Print This Post

14 Responses to 'Basic Spring Web MVC Example'

Subscribe to comments with RSS or TrackBack to 'Basic Spring Web MVC Example'.


  1. on February 12th, 2006 at 4:55 am

    […] It seems that some of you would like a graphical depiction of what’s going on in the Basic Spring Web MVC Example. Here it is: […]


  2. on February 13th, 2006 at 8:01 am

    […] You have a few Spring context configuration files, say dispatch-servlet.xml as in the Basic Spring Web MVC Example, and you want to avoid hardcoding property values. Instead of embedding them in the XML files, you want to place them in a simple property file, making life much easier for folk who use and deploy your application. In what follows, we’ll show you how to do this, and explain how it works by diving into the IoC container. […]


  3. on February 16th, 2006 at 2:28 am

    […] As explained in Basic Spring Web MVC Example and Basic Web MVC Example - In Pictures, Spring’s dispatcher servlet uses a URL mapper to map requests that come into the dispatcher servlet to appropriate handlers. Indeed, the example application used a ’simple URL mapper’ that mapped all requests to the same handler. Despite its name, this is one of the better handlers, so in this entry we will explore how to configure the URL handler. Along the way we’ll learn about factory beans, and the PropertiesFactoryBean in particular. […]


  4. on February 17th, 2006 at 8:00 am

    […] We’ll walk through the configuration by looking at the changes made to skeleton1, introduced in Basic Spring Web MVC Example. […]


  5. on March 11th, 2006 at 5:50 am

    […] Basic Spring Web MVC Example […]


  6. on March 17th, 2006 at 10:13 am

    […] Basic Spring Web MVC Example […]

  7. Arvind said,

    on August 1st, 2006 at 2:19 am

    Hi ,

    Is it possible to have a multiple Spring applications in which a user can call one Spring application from another? If S, can u please throw more light on it?

  8. Lakshminath said,

    on March 14th, 2007 at 10:18 pm

    hello,
    Is there any possibility to take multiple number of viewresolvers at a time, if so how to do that….

  9. Ritesh said,

    on August 9th, 2007 at 5:15 am

    i Like the Basic Way of explanig Spring Mvc.

  10. Harsh said,

    on October 8th, 2007 at 8:23 am

    Thanks a lot.Its really a nice example for exploring sporings mvc.
    Good Job !

  11. Ziya said,

    on October 24th, 2007 at 12:46 am

    This is a good place to study basics of spring. Thanks

  12. Suresh said,

    on February 8th, 2008 at 11:19 am

    HI

    This is very good example to start Spring MVC application.

    Iam really appriciating forr this Good Job.

  13. Rich said,

    on July 22nd, 2008 at 12:06 pm

    You wouldn’t believe how many years I’ve been looking for a way to get past the entry barrier to spring, this simple example has finally done it for me, thanks!

    I did have to add spring-xxx/dist/modules/spring-webmvc.jar to my classpath though.

  14. Prarthana said,

    on August 21st, 2008 at 11:34 pm

    Extremely useful. I have been looking out for a site which would develop a small application with basic explanation. This made he concepts very clear.

Leave a Reply