Wednesday, February 16, 2011

Spring Framework (Setup and Configuration)

Developing software applications is hard enough even with good tools and technologies. Implementing applications using platforms which promise everything but turn out to be heavy-weight, hard to control and not very efficient during the development cycle makes it even harder. Spring provides a light-weight solution for building enterprise-ready applications, while still supporting the possibility of using declarative transaction anagement, remote access to your logic using RMI or web services, and various options for persisting your data to a database. Spring provides a full-featured MVC framework, and transparent ways of integrating AOP into your software.
Spring could potentially be a one-stop-shop for all your enterprise applications; however, Spring is modular, allowing you to use just those parts of it that you need, without having to bring in the rest. You can use the IoC container, with Struts on top, but you could also choose to use just the Hibernate integration code or the JDBC abstraction layer. Spring has been (and continues to be) designed to be non-intrusive, meaning dependencies on the framework itself are generally none (or absolutely minimal, depending on the area of use).
I am going to explain some parts of spring 3.0.4 in my future posts. This post is specified to Spring MVC.
Spring MVC is an action base presentation framework. To configure this, we should follow these spteps:
  1. Spring has a global servlet named "org.springframework.web.servlet.DispatcherServlet" we can use this to map all requests to this servlet. From here Spring MVC is started.
  2. <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns="http://java.sun.com/xml/ns/javaee"
               xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
               xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
              http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
               version="2.5">

        <context-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/applicationContext.xml</param-value>
        </context-param>
        <listener>
            <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
        </listener>
        <servlet>
            <servlet-name>spring</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <init-param>
                <param-name>contextConfigLocation</param-name>
                <param-value>
                    classpath:spring-servlet.xml
                </param-value>
            </init-param>
            <load-on-startup>1</load-on-startup>
        </servlet>
        <servlet-mapping>
            <servlet-name>spring</servlet-name>
            <url-pattern>*.html</url-pattern>
        </servlet-mapping>
    </web-app>
    "contextConfigLocation" is a property which take spring context configuration path. if we do not specify this property for "DispatcherServlet", this servlet will assume "[servletname]-servlet.xml" file. But in this configuration we specify "classpath:spring-servlet.xml". It means the spring context configuration is placed in the root of classes path. we also have two spring context in this configuration. Another is "applicationContext.xml". If we are not going to use Spring MVC it does not necessary to specify this context unless we need it. Most projects have only one spring context.
  3. In "spring-servlet.xml" file we should define spring beans classes and other spring configuration. One of the most important spring beans are spring components. "Controller", "Service", "Repository" are derived "Component" which have their own uses. we can specify custom classes as some components in this context one by one or make the spring to scan from a root to scan and make them in annotation base of spring.
  4. <?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:context="http://www.springframework.org/schema/context"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

        <context:component-scan base-package="com.springtest"/>

        <!--Tiles 2-->
        <bean id="tilesConfigurer" class="org.springframework.web.servlet.view.tiles2.TilesConfigurer">
            <property name="definitions">
                <list>
                    <value>/WEB-INF/layout/tiles-config.xml</value>
                </list>
            </property>
        </bean>

        <bean id="tilesViewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
            <property name="viewClass" value="org.springframework.web.servlet.view.tiles2.TilesView"/>
            <property name="order" value="1"/>
        </bean>
    </beans>
    In this configuration we make spring to scan all components from "com.springtest". Then a bean is created from "org.springframework.web.servlet.view.tiles2.TilesConfigurer" class called "tilesConfigurer". In spring it does not need to create any bean. we can let spring to do that then we request to spring to provide us the bean. Another bean name is "tilesViewResolver" from "org.springframework.web.servlet.view.tiles2.TilesView". This bean has a property called "viewClass" which is set to "org.springframework.web.servlet.view.tiles2.TilesView" and the other property is "order" which is set to "1". when we configure "tilesViewResolver" in our context, we notify Spring MVC that the return address are tiles address with priority of and should looks for it in our tiles configuration. So it uses the "tilesConfigurer" bean to find the tiles configuration. we can have other view resolvers like "VelocityViewResolver", "FreeMarkerViewResolver" and etc.
  5. There is a tiles configuration in "/WEB-INF/layout/tiles-config.xml"
    <?xml version="1.0" encoding="ISO-8859-1" ?>
    <!DOCTYPE tiles-definitions PUBLIC
            "-//Apache Software Foundation//DTD Tiles Configuration 2.0//EN"
            "http://tiles.apache.org/dtds/tiles-config_2_0.dtd">
    <tiles-definitions>
        <definition name="*.view" template="/WEB-INF/layout/view.jsp">
            <put-attribute name="body" value="/WEB-INF/pages/{1}/{1}-view.jsp"/>
        </definition>
        <definition name="*.list" template="/WEB-INF/layout/view.jsp">
            <put-attribute name="body" value="/WEB-INF/pages/{1}/{1}-list.jsp"/>
        </definition>
    </tiles-definitions>
    This configuration maps any return value to these patterns "*.view"  or "*.list" if it is fitted, forward to the specified jsp.
  6. finally we need Controller class.
    package com.springtest;

    import org.springframework.stereotype.Controller;
    import org.springframework.context.annotation.Scope;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.ModelAttribute;
    import org.springframework.ui.Model;
    import com.springtest.domain.FirstDomain;

    @Controller
    @Scope("prototype")
    @RequestMapping("/first")
    public class FirstSpringController {
        @ModelAttribute("first")
        public FirstDomain createModel(){
            return new FirstDomain();
        }

        @RequestMapping("/view")
        public String view(Model model){
            FirstDomain firstDomain = (FirstDomain) model.asMap().get("first");
            firstDomain.setText("Hello World ...");
            return "first.view";
        }
    }
    First we should annotate it by "@Controller" annotation. after this annotation the spring context assume this class as spring bean controller. The "@Scope" annotation set it as installable bean in spring AOP. the default is singleton. "@RequestMapping" annotation maps any action to this class or method. if the "@RequestMapping" is placed on top of the class definitions, "@RequestMapping" of the methods will be continue of that. for example in this class "/view" action is mapped when action starts with "/first" like "/first/view.html" action.
I will describe more about Spring framework and Spring MVC in my next posts.
You can download the full source code of above sample. after you run it in an application server like tomcat, the first page url is: http://localhost:8080/first/view.html


all rights reserved by Mostafa Rastgar and Programmer Assistant weblog

No comments: