Monday, September 12, 2011

Web Application Development using Spring MVC

Spring MVC helps you to build web based applications that are as flexible and as loosely coupled as the Spring Framework itself.

Spring MVC Life Cycle



When the request leaves the browser, it carries information about what the user is asking for. At least, the request will be carrying the requested URL. But it may also carry additional data such as the information submitted in a form by the user.

The first stop in the request’s travels is at Spring’s DispatcherServlet. Like most Java-based web frameworks, Spring MVC funnels requests through a single front con-troller servlet. A front controller is a common web application pattern where a single servlet delegates responsibility for a request to other components of an application to perform actual processing. In the case of Spring MVC, DispatcherServlet is the front controller.

The DispatcherServlet’s job is to send the request on to a Spring MVC controller. A controller is a Spring component that processes the request. But a typical applica-tion may have several controllers and DispatcherServlet needs some help deciding which controller to send the request to. So the DispatcherServlet consults one or more handler mappings to figure out where the request’s next stop will be. The handler mapping will pay particular attention to the URL carried by the request when making its decision.

Once an appropriate controller has been chosen, DispatcherServlet sends the request on its chosen controller. At the controller, the request will drop off its payload (the information submitted by the user) and patiently wait while the controller processes that information. (Actually, a well-designed controller per forms little or no processing itself and instead delegates responsibility for the business logic to one or more service objects.)

The logic performed by a controller often results in some information that needs to be carried back to the user and displayed in the browser. This information is referred to as the model. But sending raw information back to the user isn’t sufficient, it needs to be formatted in a user-friendly format, typically HTML. For that the information needs to be given to a view, typically a JSP.

One of the last things that a controller does is package up the model data and identify the name of a view that should render the output. It then sends the request, along with the model and view name, back to the DispatcherServlet.

The view name passed back to DispatcherServlet doesn’t directly identify a specific JSP. In fact, it doesn’t even necessarily suggest that the view is a JSP at all. Instead, it only carries a logical name which will be used to look up the actual view that will produce the result. The DispatcherServlet will consult a view resolver to map the logical view name to a specific view implementation, which may or may not be a JSP. Now that DispatcherServlet knows which view will render the result, the request’s job is almost over.Its final stop is at the view implementation (probably a JSP) where it delivers the model data. The request’s job is finally done. The view will use the model data to render output that will be carried back to the client by the (not- so-hardworking) response object

Setting up Spring MVC
At the heart of Spring MVC is DispatcherServlet, a servlet that functions as Spring MVC’s front controller. Like any servlet, DispatcherServlet must be configured in the web application’s web.xml file. So the first thing we must do to use Spring MVC in our application is to place the followingdeclaration in the web.xml file:

 <servlet>
        <servlet-name>Spring MVC</servlet-name>
   <servlet-class> org.springframework.web.servlet.DispatcherServlet   </servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/spring.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
  </servlet>

To test the example Create a new Dynamic Web Project with Name SpringProGo to WEB-INF folder and create a file with name web.xml Add Dispatcher Servlet Code in web.xml

By default, when Dispatcher- Servlet is loaded, it’ll load the Spring application context from an XML file whose name is spring.xml(located in the application’s WEB-INF directory).
Next Step is to Map the Servlet

    <servlet-mapping>
        <servlet-name>Spring MVC</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

By mapping DispatcherServlet to /, I’m saying that it’s the default servlet and that it’ll be responsible for handling all requests, including requests for static content.Next Step is to create the spring.xml file that Dispatcher- Servlet will use to create an application context. The following listing shows the beginnings of the spring.xml file

<?xml version="1.0" encoding="UTF-8"?>
 <beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:mvc="http://www.springframework.org/schema/mvc"
 xsi:schemaLocation="http://www.springframework.org/schema/mvc
 http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
 http://www.springframework.org/schema/beans
 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
       <mvc:resources mapping="/resources/**" location="/resources/"/>
 </beans>

<mvc:resources> sets up a handler for serving static content. The mapping attribute is set to /resources/**, which includes an Ant-style wildcard to indicate that the path must begin with /resources, but may include any sub path thereof. The location attribute indicates the location of the files to be served. As configured here, any requests whose paths begin with /resources will be automatically served from the /resources folder at the root of the application. Therefore all of our images, style sheets, JavaScript, and other static content needs to be kept in the application’s /resources folder.

Configuring an annotation-driven Spring MVC

As I mentioned earlier, DispatcherServlet consults one or more handler mappings in order to know which controller to dispatch a request to. Spring comes with a hand- ful of handler mapping implementations to choose from, including
  • BeanNameUrlHandlerMapping—Maps controllers to URLs that are based on the controllers’ bean names.
  • ControllerBeanNameHandlerMapping—Similar to BeanNameUrlHandlerMapping, maps controllers to URLs that are based on the controllers’ bean names. In this case, the bean names aren’t required to follow URL conventions.
  • ControllerClassNameHandlerMapping—Maps controllers to URLs by using the controllers’ class names as the basis for their URLs.
  • DefaultAnnotationHandlerMapping—Maps request to controller and control- ler methods that are annotated with @RequestMapping.
  • SimpleUrlHandlerMapping—Maps controllers to URLs using a property collec- tion defined in the Spring application context.
If no handler mapping beans are found, then DispatcherServlet creates and uses BeanNameUrlHandlerMapping and DefaultAnnotationHandler- Mapping.
To enable annotation for the project you need to add simply one line in splitter-servlet.xml
<mvc:annotation-driven/>
For our application HomeController is a basic Spring MVC controller that handles requests for the home page.
package com.springpro.controller;
import java.util.Map;
import javax.inject.Inject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.springpro.service.SpitterService;

@Controller
public class HomeController {

public static final int DEFAULT_SPITTLES_PER_PAGE=25;
private SpitterService spitterService;
@Inject
public HomeController(SpitterService spitterService){
this.spitterService=spitterService;
}

@RequestMapping({"/","/home"})
public String showHomePage(Mapmodel){
System.out.println("Reached here");
model.put("spittles",spitterService.getRecentSpittles(DEFAULT_SPITTLES_PER_PAGE));
return "home";
}
}
Although HomeController is simple, there’s a lot to talk about here. First, the @Controller annotation indicates that this class is a controller class.
Also we need to configure a <context:component-scan> in spitter- servlet.xml so that the HomeController class (and all of the other controllers we’ll write) will be automatically discovered and registered as beans. Here’s the relevant snippet of XML
<context:component-scan base-package="com.springpro.contoller"/>
Going back to the HomeController class, we know that it’ll need to retrieve a list of the most recent spittles via a SpitterService. Therefore, we’ve written the constructor to take a SpitterService as an argument and have annotated it with @Inject annota-tion so that it’ll automatically be injected when the controller is instantiated.
Spring.xml should look like this
<?xml version="1.0" encoding="UTF-8"?>
 <beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:mvc="http://www.springframework.org/schema/mvc"
 xmlns:context="http://www.springframework.org/schema/context"
 xsi:schemaLocation="http://www.springframework.org/schema/mvc
 http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
 http://www.springframework.org/schema/context
 http://www.springframework.org/schema/context/spring-context-3.0.xsd
 http://www.springframework.org/schema/beans
 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
  <mvc:resources mapping="/resources/**" location="/resources/" />
  <mvc:annotation-driven/>
  <context:component-scan base-package="com.springpro"/>
  <bean>
  <property name="prefix" value="/WEB-INF/views/"/>
  <property name="suffix" value=".jsp"/>
 </bean>
 </beans>
To display records in JSP
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@taglib prefix="s" uri="http://www.springframework.org/tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
 Top of the Page.
 <c:forEach var="spittle" items="${spittles}">
   <br><c:out value="${spittle}"></c:out>
 </c:forEach>
</body>
</html>
Source (Spring in Action 3)

10 comments:

  1. There are actually a variety of details like that to take into consideration. That could be a nice point to carry up. I provide the thoughts above as general inspiration however clearly there are questions like the one you deliver up where a very powerful factor can be working in trustworthy good faith. I don?t know if finest practices have emerged around issues like that, however I'm positive that your job is clearly recognized as a good game. Both boys and girls really feel the impact of only a second’s pleasure, for the rest of their lives.

    ReplyDelete
  2. I really appreciate the way you discuss this kind of topic

    ReplyDelete
  3. I cherished up to you'll obtain performed right here. The cartoon is tasteful, your authored subject matter stylish. nevertheless, you command get bought an nervousness over that you want be delivering the following. in poor health for sure come further formerly once more as precisely the similar nearly a lot incessantly inside of case you protect this increase.

    ReplyDelete
  4. I've been surfing on-line more than three hours as of late, but I never found any attention-grabbing article like yours. It?s lovely price enough for me. Personally, if all website owners and bloggers made good content as you did, the net will probably be much more helpful than ever before.

    ReplyDelete
  5. That is the correct weblog for anybody who desires to find out about this topic. You realize so much its virtually hard to argue with you (not that I really would need…HaHa). You positively put a new spin on a subject thats been written about for years. Great stuff, simply nice!

    ReplyDelete
  6. F*ckin? tremendous things here. I?m very glad to see your post. Thanks a lot and i'm taking a look forward to touch you. Will you please drop me a e-mail?

    ReplyDelete
  7. Can I just say what a reduction to seek out somebody who really is aware of what theyre talking about on the internet. You positively know learn how to bring an issue to mild and make it important. Extra people need to learn this and perceive this facet of the story. I cant believe youre not more common since you definitely have the gift.

    ReplyDelete
  8. "More than kisses, letters mingle souls." ~ John Donne

    ReplyDelete
  9. Custom software development, companies can get software applications and web applications developed according to the business needs.web application or software can be customized as per business requirement So Spring MVC helps to build web based applications.This is such a great resource that you are proving.
    Web Development Company

    ReplyDelete
  10. very very nice webBlog...very helpful for Beginners like me

    ReplyDelete