Saturday, January 14, 2012

Adding Spring MVC to Spring Web Services Part 2

In this example we will create a Person request handled by Spring MVC framework. Towards the end, I will summarize how both Spring MVC and Spring Web Services can be in the same application but used differently.
  1. Create an entry point into your Web Application. We will create a simple HTML file

  2. Create welcome-file in your web.xml

  3. Now lets add Spring to our application. In web.xml add a front controller mapping for Spring. This controller will control where all requests are routed based on configuration we will set up later.

    • Line 2 - Servlet name will be used for our Spring configuration files
    • Line 3 - DispatcherServlet used as a front controller
    • Line 8 - Any URL that ends with .htm will be served by DispatcherServlet
  4. Create configuration file used by DispatcherServlet containing definitions for all beans. The name of the file is derived from using servlet-name defined in web.xml and appending "-servlet".

    Here we have defined a bean (/person.htm) with a mapping to a Page Controller, which is responsible for handling a request for a particular page of the website. HandlerMapping is an interface that maps between a request URL and the object that is going to handle that request (the handler). The default handler for DispatcherServlet is BeanNameUrlHandlerMapping which uses the bean name defined in this config file to map to the URL in the request so that the DispatcherServlet knows which controller must be invoked for handling different URLs.
  5. Create PersonController

    Since we have not explicitly defined a ViewResolver, we are going to be given a default one by Spring that simply forwards to a URL matching the name of the view specified.
  6. Create Person view, this is the view that is returned by the PersonController. Because we are using a default ViewResolver, place this file in your WebContent folder (outside of WEB-INF)

  7. List of JARs
    • commons-logging
    • spring.web.servlet
    • spring.web-3.1.0
  8. Test Controller

  9. Deploy your application on a Server. Hit the URL: http://localhost:8080/MyWebServices/person.htm

No comments:

Post a Comment