They know enough who know how to learn

Monday, February 23, 2009

Basic Spring Web MVC Example

Here I will create a simple web application that utilizes spring's web MVC framework. Although this POC does not utilize all of the features of spring-MVC, it is a good to start with a simple application. This will be helpful to start my expedition to discover more about spring MVC

Background


 

When starting to create a simple web application, you need a few essentials:

A dispatcher servlet will intercept incoming requests in the web application.

A configuration that instructs the web container to route requests to the dispatcher servlet (i.e. a servlet mapping)

Controllers (the C in MVC) are there to perform the business logic. Controller routes to particular views (the V in MVC); this routing perhaps convey information models (the M in MVC).

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

How to do it and how it works

As starting point 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>DispatcherServlet </servlet-name>

<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

<load-on-startup>1</load-on-startup>

</servlet>

<servlet-mapping>

<servlet-name> DispatcherServlet </servlet-name>

<url-pattern>/*</url-pattern>

</servlet-mapping>


 


 

Although above description does not need any explanation but this title text will help to understand what does it mean to declare a mapping resource in web.xml.


 

This says: Create the servlet for me, call it DispatcherServlet, and map all incoming URLs to this servlet. So for example, a URL such as http://.../appname/welcome would activate the DispatcherServlet.


 

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 DispatcherServlet, it looks for a file called DispatcherServlet-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.


 

Controller


 

<bean id="welcomeController " class="com.stpl.poc.springmvc.WelcomeController" />

How controller perform its operations in spring based application will be described later; just go ahead without worrying about

View Resolver

The view resolver tells us how to rend 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 welcome," then the above resolver would try to find the file welcome.jsp in /WEB-INF/views. This is easy and extensible.

URL mapping

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?

<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">

<property name="mappings">

    <props>

            <prop key="/welcome">welcomeController</prop>

        </props>

</property>

</bean>


 

This again uses a Spring-supplied URL mapper, as you can see, which maps all requests (/welcome) to the controller called welcomeController (which we defined above).

Controller continued

The last key to understand here 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 with /welcome to the welcomeController).

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:.../pocapp/welcome then it will try to invoke the method wecome() on welcomeController.

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("welcome");


 

        mav.addObject("message", "Hi I am your web allocation manager. You have got everything right till now!");


 

        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 welcome.jsp, and yes, that's what we have. Here's a look at it:


 

Hello, you're in welcome.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://../pocapp/welcome 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.

No comments:

Post a Comment