ManagedCloud Servers

High performance handled and monitored by us 24/7/365. A complete solution to provide you with our in house expertise 24/7 tailored to your specific needs. We'll setup a bespoke server for your site using the latest tehnologies so you can get the most out of your hardware and get your website loading quickly and reliably. Find out more..

cPanelCloud Servers

Recommended - High performance cloud servers with no technical knowledge required. If you're hosting multiple websites already and you're looking to consolidate, or if you're looking to isolate yourself from the shared hosting environment but you don't have the time or knoweldge to manage a server, then the Managed cPanel Servers are for you. Find out more..

UnmanagedCloud Servers

Our unmanaged range gives you complete control at rock bottom prices and our cloud platform boasts super fast multipath 40Gb/s network, the latest Intel Xeon V3 CPUs and enterprise grade redundant SSDs. If you're a sysadmin look no further, we offer some of the best specification to price ratio servers available. Find out more..

Need Web Hosting? Try ours, it's fast, reliable and feature loaded with support you can depend on. From £1.60 / month.

View Plans

An Introduction to Spring

Spring is a lightweight container with wrappers that make it easy to use many different services and frameworks. Spring uses the Inversion of Control and Dependency Injection patterns. Components and frameworks can be wired together using simple java beans and XML declarations or via annotations. This tutorial shows you how to use ANT and XDoclet to package your Spring based applications to JBoss. The idea behind the Spring container is that it accepts any JavaBean, As long as the Spring wrappers have getters and setters like a JavaBean then they can be easily used by the Spring container.

Inversion of Control pattern.

Inversion means that the control of the application has been inverted or moved into the framework API. Spring also uses the Dependency Injection pattern. The Dependency Injection pattern is a subset of Inversion of Control. There are three main types of dependency injection: (i) Constructor injection (ii) Interface injection (iii) Setter injection Spring supports Constructor and Setter injection. Most developers prefer and use Setter injection. Setter injection involves creating wrapper classes for the underlying technologies. The wrapper classes are given setter and getter methods just like a JavaBean. A typical Spring JavaBean has dependencies on other JavaBeans. The relationships between the different beans are defined in an XML file or via Annotations (most preferred). The developer asks the Spring framework for a specific JavaBean.Spring looks up the logical name of a parent JavaBean in the bean Configuration. If that JavaBean has dependencies on other child JavaBeans then the following steps occur: The child JavaBeans are instantiated and set in the parent JavaBean. The setter methods of the parent JavaBean are called to set the child JavaBeans in itself. The parent JavaBean is returned to the calling code. Spring supports many different components and can be used either in conjunction with a J2EE Application Server such as JBoss or in many cases (depending on the component) in a standalone setup.

Objectives

The main objective of this course is to get you up to speed with the fundamentals of the Spring Framework. There are 2 examples in this course which are well explained for study. One of the principles of this course is learning by example. This course aims to be quite self-sufficient.

Understanding Spring

The Spring Framework contains seven modules. We will go through each module briefly in this section.

Spring Core

The Spring Core module contains the core functionality of the framework, including the Dependency Injection feature and classes to manage the configuration files.

Spring Context

The Spring Context module sits on top of the Spring Core module to provide a way to access components in a framework-style manner.

Data Access/Integration

The Spring DAO module provides a JDBC abstraction layer that does away with JDBC coding and parsing of database-vendor specific error codes.

Spring ORM

The Spring ORM module provides an integration layer for popular object-relational mapping APIs, including iBATIS, Hibernate, and JDO.

Spring AOP

The Spring AOP module provides support for implementations of aspect-oriented programming (AOP). In object-oriented programming, a large application is broken down into distinct parts that overlap in functionality as little as possible. For example, packages, classes, and methods all help us to encapsulate different functionalities into distinct entities. However, some functions cut across all distinct entities, e.g. logging, security handling, transaction handling, etc. Different classes may have the same logging concerns. What happens if we change the logging strategy? Without AOP, we will have to change all the classes that have the logging function. AOP solves this problem by adding new programmatic syntax to deal with functions that cut across different entities. This is the extent of our discussion of AOP for this tutorial.

Spring Web

The Spring Web module provides basic web-oriented integration features, with support for Struts or WebWork.

Spring Web MVC

The Spring Web MVC module provides a Model-View-Controller implementation for web applications.

Dependency Problems

Commercial Java/J2EE applications comprise a collection of collaborating components (or objects). It is not uncommon to have different teams working on separate components at the same time. When this is the case, a key problem will be the management of dependencies among the components.

To enable effective team collaboration on such projects, we must adhere to the key modularity principle in object-oriented design, i.e. the principle of locality-of-impact: A change in a component should impact as few other components as possible. It should be possible to develop and test a component as independently as possible. When a component (Component 1) depends on another component (Component 2), how does it obtain a reference to an instance of Component 2 during development and testing? Remember: Component 2 may or may not be available yet because it could be developed by another team.

Dependency management approaches

There are several approaches that we can take to solve this problem: 1. Direct referencing 2. Factories 3. Service locator 4. Inversion of control/dependency injection

Direct Referencing

The easiest solution is to call the constructor of Component 2 within the implementation of Component 1. The problem with this approach is as follows: 1. It violates the principle of locality-of-impact. 2. Changes to Component 2 will impact all other components that depend on it. 3. The initialization of Component 2 becomes the responsibility of all other components that depend on it. If the constructor of Component 2 has initialization parameters, they have to be made known to all those components. If Component 2 changes its constructor, all other components that depend on it will not compile. 4. Unit testing of Component 1 depends on the availability of Component 2 (or a stubbed version of Component 2).

Factories

This is a traditional design pattern and uses interfaces (rather than concrete classes) and abstract factory objects to solve the dependency problem. In this approach, Component 1 can call the factory for Component 2, which will return the interface for Component 2. Changes in the implementation of Component 2 will not affect Component 1. The problem with this approach is as follows: This solution does not address the initialization issue described in the previous section. For every component that we develop, there must be a corresponding factory class for it. Unit testing for Component 1 depends on the availability of the factory for Component 2.

Service Locator

A variant of the factory design pattern is the service locator. This approach removes the dependency on individual factory classes. Instead, it uses the service locator as a super-factory that is capable of manufacturing objects of many different types. However, there are still downsides: 1. The service locator must be updated every time we add a new component. 2. The service locator is not type-safe. In order for it to manufacture objects in a generic way, it must return a java.lang.Object or a superclass object. It is up to the components that use it to cast the return object to the right type. 3. Every component that uses the service locator is dependent on it.

Inversion of Control/Dependency Injection

This is a solution that we prefer. Inversion of control (IOC) is a design pattern that does away with the managing of dependencies among components. With this approach, components reference one another by their interfaces. There is a separate framework (called the dependency injection framework) that is responsible for wiring together all the dependencies among the components in the application. If Component 1 requires Component 2, the only dependency Component 1 has on Component 2 is through the latter’s interface. Component 1 does not depend on Component 2’s implementation, on its factory, on its initialization parameters, or even on the dependency injection framework. The separate dependency injection framework will be responsible for gluing Component 2 to Component 1 by: Constructing an instance of Component 2 (with the appropriate initialization parameters), Constructing an instance of Component 1 Passing the initialized instance of Component 2 to Component 1 either through a constructor parameter (called Constructor Injection) or a setter method (called Setter Injection). There are several dependency injection frameworks that we can use, e.g. Spring, PicoContainer, HiveMind etc. In addition, we can also create our own custom framework. However, we prefer to use Spring because it is open source, more mature, has more widespread adoption, and has a richer feature set.

Advantages of Spring

  1. The application code becomes simpler because we don’t have to deal with the component wiring logic.
  2. It is easier to develop and maintain software components across multiple teams.
  3. It is easier to test software components.
  4. All the component wiring details are stored in standard XML files or via annotations for easy configuration.
  5. It provides support for dependency injection into EJBs.
  6. It provides support for popular persistence frameworks like Hibernate and iBATIS.
  7. It is fast.

Getting Started

In this section, we shall download and install the Spring Framework. You need to have the Java SDK and the Eclipse IDE before you begin. Download the current production release of the Spring Framework from here Unzip the downloaded file to a location in your computer (e.g. C:\Tools\springframework).(in this tutorial we are using ant to manage Spring dependency all you need is to have spring Jar files in a folder. If you Know how to us Maven or ivy they can download all jar files for you)

Install Spring IDE

The Spring IDE is a plug-in for Eclipse that provides a graphical user interface for the configuration files used by the Spring Framework. While it is not a mandatory tool, it is nevertheless a useful one as it allows you to present your Spring configuration files in graphs. To enable Spring support within Eclipse for a particular project, right-click on the project in Package Explorer and choose Add Spring Project Nature. Once you have done so, the project will appear in the Spring Beans tab. Right-click on the project and choose Properties, then go to the Spring properties. Click the Add button to add all spring configuration files in the project to the Spring Beans tab, and then click OK. You should now be able to see the files represented in a tree structure. To represent a configuration file in a graph, right-click on the file in the Spring Beans tab and choose Show Graph.

Example One: Spring MVC

This example introduces you to: (i) application.xml (ii) web.xml (iii) Spring config file (ends in “-servlet.xml”) (iV) org.springframework.web.servlet.mvc.Controller (V) org.springframework.web.servlet.handler.SimpleUrlHandlerMapping (Vi) org.springframework.web.servlet.ModelAndView

Dependencies

This example requires the following software to be installed: (i) JDK 1.6 or above (ii) ANT (iii)JBoss Please note that it is recommended to only install Production Release software. Also note that even Production Release software can also have bugs and sometimes it is better to use an older more stable version. It is also recommended that you have access to the following documentation on your local computer: JDK 1.6 or above documentation ANT documentation XDoclet documentation Please open a msdos window and make sure that both javac and java are the same version: Please make sure that JAVA_HOME is set correctly: Please make sure that ANT_HOME is set correctly: Please make sure that the correct JDK and ANT is in your PATH variable: Please make sure that you have told ANT where Jboss is. Edit :

spring_mvc_1\trunk\SVN_LOCAL\masterbuild\config.run.properties

so that the variable, absolute.appserver.home.dir points to jboss.

absolute.appserver.home.dir=C:/jboss

It is good practise that you make the above checks every time you work on a new machine. For example having different versions of javac and java can create issues that sometimes are difficult to interpret. It is recommended that you use Eclipse as your IDE. This course does not make use of any Eclipse plugins. Instead it automates tasks using ANT and XDoclet

When using eclipse it is preferable that you put all of your java projects under the same directory. This means they can be in the same Workspace and you can open multiple projects and copy files from one project to another. For example my java projects can be found under: C:\JACKSON\DATA\java_projects

The spring jar libraries should be in folder : C:\JACKSON\DATA\java_projects\lib

Run application

The following command will deploy your application and start jboss.

spring_mvc_1\trunk\SVN_LOCAL\masterbuild>ant clean jboss.clean deploy.ear jboss.start

Notice that the above ANT command does the following: 1. Cleans past ANT generated files for the project 2. Deletes all past deployments to JBoss 3. Builds the ear file 4. Deploys the ear file to JBoss 5. Starts JBoss

To access the application open your browser and type: http://localhost:8080/spring_mvc_1/ Click on the links – you will notice that the resulting pages explain what is going on. This course expects you to already understand a minimum of ANT and XDoclet.

application.xml

application.xml is a deployment descriptor for an ear file. The spring application is being packaged in a war file and the war file is placed in the ear file.

The important part of this file is:

     <module>
        <web>
                <web-uri>spring_mvc_1.war</web-uri>
                <context-root>spring_mvc_1</context-root>
        </web>
     </module>

application.xml ends up being added to the meta-inf directory of the ear file that is created. Its purpose in this example is to tell the application server what context the web application should run under.
You can see the ANT task that uses the application.xml in the ANT file:

     <?xml version="1.0" encoding="ISO-8859-1"?>
     <project name="ear" basedir="." default="info">  
                <target name="ear.create.ear" 
                        depends="web.create.war"> 
                <ear destfile="${absolute.ear.dist.ear.name}" 
                appxml="${absolute.ear.src.meta-inf.application.xml.name}">
                    <fileset dir="${absolute.web.dist.dir}">
                        <include name="${web.war.name}"/>
                    </fileset>           
                </ear>
                </target>  
        <target name="deploy.ear" description="deploys ear" 
                depends="ear.create.ear">  
        <copy file="${absolute.ear.dist.ear.name}"
                toFile="${absolute.ear.jboss.deploy.name}" />
        </target>
     </project>

Notice that the application.xml file is referred to by the ANT variable:

absolute.ear.src.meta-inf.application.xml.name

web.xml

Notice that web.xml was generated by ANT using XDoclet. The following parts of web.xml will now be explained: 1. welcome-file-list 2. servlets 3. servet-mapping

welcome-file-list

You can see the following in web.xml:

    <welcome-file-list>
            <welcome-file>jsp/index.jsp</welcome-file>
    </welcome-file-list>

This means that if the user types: http://localhost:8080/yourspringapp the request will be re-directed to:http://localhost:8080/yourspringapp/jsp/index.jsp XDoclet merged the welcome-file-list into the generated web.xml file.

servlets

In web.xml:

     <servlet>
            <servlet-name>springapp</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
            <load-on-startup>1</load-on-startup>
     </servlet>

XDoclet merged the servlet into the generated web.xml file.

servlet-mapping

In web.xml:

     <servlet-mapping>
            <servlet-name>springapp</servlet-name>
            <url-pattern>*.spring</url-pattern>
     </servlet-mapping>

It tells the application server that URLs that end in that match the pattern *.spring should be serviced by the springapp Servlet. The springapp Servlet is defined in the servlet section of the web.xml and maps to the Spring class: org.springframework.web.servlet.DispatcherServlet XDoclet merged the servlet-mapping into the generated web.xml

index.jsp

A link like this in index.jsp: http://localhost:8080 /spring_mvc_1/hello.spring makes the application server recognize that the URL ends in the extension *.spring The application server looks in web.xml to see if any Servlets have registered an interest for URL extensions ending in *.spring. It finds that “org.springframework.web.servlet.DispatcherServlet” has been registered for extensions matching *.spring. The Servlet has the logical name springapp

<servlet-mapping>
    <servlet-name>springapp</servlet-name>
    <url-pattern>*.spring</url-pattern>
</servlet-mapping> 

DispatcherServlet looks for a spring configuration file under WEB-INF of the war file that uses the name springapp with servlet.xml added to the end of the name. In other words it looks for a file under WEB-INF called: springapp-servlet.xml DispatcherServlet looks in springapp-servlet.xml and sees the following:

     <beans>    
      <bean id="springappController" 
        class="com.jjpeople.springmvc.controller.SpringController"/>    
        <bean id="urlMapping" 
        class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">        
        <property name="mappings">            
        <props>
            <prop key="/hello.spring">springappController</prop>
        </props>
        </property>
      </bean>
     </beans> 

Notice that in springapp-servlet.xml, the DispatchServlet sees a bean that is using the class,

    org.springframework.web.servlet.handler.SimpleUrlHandlerMapping

The contents of SpringController look like:

    public class SpringController implements Controller {    
            public ModelAndView handleRequest(
                    HttpServletRequest request, HttpServletResponse response )            
                    throws ServletException, IOException {

return new ModelAndView("jsp/hello.jsp"); } }

Notice that the implementation of SpringController is very simple. Usually the implementation of this class would be the place where you code calls to business delegates which return data that can then be set in the request or session before being forwarded to a JSP. However in this simple example no attributes are set in the request or session and instead the request is simply forwarded to jsp/hello.jsp

Spring Fundamentals: Example Two: Spring MVC

This example uses the files we saw in Example One Spring MVC: application.xml web.xml Spring config file (ends in “-servlet.xml”) org.springframework.web.servlet.mvc.Controller org.springframework.web.servlet.handler.SimpleUrlHandlerMapping org.springframework.web.servlet.ModelAndView

It also introduces: org.springframework.web.servlet.view.InternalResourceViewResolver

This example is similar to Example One Spring MVC. Please look at Explanation of Files for Example One Spring MVC before reading this explanation.

Springapp-servlet.xml

The spring config file, springapp-servlet.xml looks like:

     <?xml version="1.0" encoding="UTF-8"?>
     <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" 
     <A href="http://www.springframework.org/dtd/spring-beans.dtd">
     http://www.springframework.org/dtd/spring-beans.dtd</A>>

<!-- - Application context definition for "springapp" DispatcherServlet. --> <beans> <bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"> <property name="mappings"> <props> <prop key="/products.spring">springappController</prop> <prop key="/priceincrease.spring">priceIncreaseForm</prop> </props> </property> </bean>

<bean id="springappController" class="com.jjpeople.springmvc.controller.SpringController"> <property name="model"> <ref bean="model"/> </property> <property name="productManager"> <ref bean="productManager"/> </property> </bean>

<!-- Validator and Form Controller for the "Price Increase" page --> <bean id="priceIncreaseValidator" class="com.jjpeople.springmvc.validator.PriceIncreaseValidator"/>

<bean id="priceIncreaseForm" class="com.jjpeople.springmvc.controller.PriceIncreaseFormController"> <property name="sessionForm"> <value>true</value> </property> <property name="commandName"> <value>priceIncrease</value> </property> <property name="commandClass"> <value>com.jjpeople.springmvc.model.PriceIncrease</value> </property> <property name="validator"> <ref bean="priceIncreaseValidator"/> </property> <property name="formView"> <value>priceincrease</value> </property> <property name="successView"> <value>products.spring</value> </property> <property name="productManager"> <ref bean="productManager"/> </property> </bean> <bean id="model" class="com.jjpeople.springmvc.model.Model"/>

<beanid="productManager" class="com.jjpeople.springmvc.delegate.ProductManager"> <property name="products"> <list> <ref bean="product1"/> <ref bean="product2"/> <ref bean="product3"/> </list> </property> </bean>

<bean id="product1" class="com.jjpeople.springmvc.model.Product"> <property name="description"> <value>Lamp</value> </property> <property name="price"> <value>5.75</value> </property> </bean>

<bean id="product2" class="com.jjpeople.springmvc.model.Product"> <property name="description"> <value>Table</value> </property> <property name="price"> <value>75.25</value> </property> </bean>

<bean id="product3" class="com.jjpeople.springmvc.model.Product"> <property name="description"> <value>Chair</value> </property> <property name="price"><value>22.79</value></property> </bean>

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

<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"> <property name="basename"><value>messages</value></property> </bean> </beans>

Note that this config file relates to the web.xml file. In web.xml, a Spring DispatcherServlet is defined:

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

The DispatcherServlet looks for a config file under WEB-INF which uses the name of the servlet. In this case the name of the servlet is springapp and the DispatcherServlet appends -servlet.xml on the end when searching for the xml file. Having found the file springapp-servlet.xml, the DispatcherServlet looks for a bean that uses the URL mapping classes. In this example it finds a bean that uses the class, org.springframework.web.servlet.handler.SimpleUrlHandlerMapping. The bean id of this class in this example is urlMapping but it could have been named anything. The urlMapping bean looks like:

        <bean id="urlMapping" 
              class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">        
            <property name="mappings">            
            <props>
                    <prop key="/products.spring">springappController</prop>
                <prop key="/priceincrease.spring">priceIncreaseForm</prop>
            </props>
            </property>
        </bean>

Notice that it maps URLs of the format "/products.spring to the springappController bean. The springappController bean looks like:

        <bean id="springappController" 
           class="com.jjpeople.springmvc.controller.SpringController">
            <property name="model">
            <ref bean="model"/>
            </property>   
            <property name="productManager">
            <ref bean="productManager"/>
            </property>
        </bean>

Notice that it has dependencies on two other beans; model and projectManager. The Model class is instantiated and set in the SpringController using the setModel(..) method of the SpringController. A productManager bean would look like:

        <bean   id="productManager" class="com.jjpeople.springmvc.delegate.ProductManager">
            <property name="products">
            <list>
                <ref bean="product1"/>
                <ref bean="product2"/>
                <ref bean="product3"/>
            </list>
            </property>
        </bean>

The ProductManager dependencies are first of all instantiated and then set in the ProductManager using the setter method, setProducts(..). Finally, ProductManager is set in SpringController using the setter method, setProductManager(..). The SpringController is now set with its dependent objects and the DispatchServlet now calls the handleRequest(..) method of the SpringController:

public ModelAndView handleRequest(
            HttpServletRequest request, HttpServletResponse response )            
                throws ServletException, IOException {        
       this.model.setTimeNow( new Date() );
        this.model.setProducts( this.productManager.getProducts() );
        this.model.setProductTotal( this.productManager.getTotalCost() ); 
        logger.debug( "**** Debugging Model:\n" + model );
         return new ModelAndView( "products", "model", model );
    }

The handleRequest(..) method explicitly sets some further data in the Model class and then forwards the model class to the view called “products”.

SpringController

Notice that in the previous example the implementation of the handleRequest(..) method in SpringController looked like:

 public ModelAndView handleRequest(
 HttpServletRequest request, HttpServletResponse response )            
                throws ServletException, IOException {        
           return new ModelAndView("jsp/hello.jsp");   
   }

In this example the implementation of the handleRequest(..) method in SpringController is slightly different:

  public ModelAndView handleRequest(
            HttpServletRequest request, HttpServletResponse response )            
                throws ServletException, IOException {        
          this.model.setTimeNow( new Date() );
        this.model.setProducts( this.productManager.getProducts() );
        this.model.setProductTotal( this.productManager.getTotalCost() );      
        logger.debug( "**** Debugging Model:\n" + model );         
        return new ModelAndView( "products", "model", model );
    }

The main differences are as follows: Difference 1: ModelAndView uses a logical mapping for finding view pages. Look at ModelAndView. You will notice that the ModelAndView now has three arguments instead of one. In the previous example the ModelAndView mapped directly to a JSP. In this example ModelAndView uses a InternalResourceViewResolver to map the logical name “products” to “/WEB-INF/jsp/products.jsp”. This is how it does the mapping: Notice that we now have a bean with an id called “viewResolver”:

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

The logical name “products” is resolved to the URL, “WEB-INF/jsp/products.jsp” using the viewResolver.

public ModelAndView handleRequest(
            HttpServletRequest request, HttpServletResponse response )            
                throws ServletException, IOException {        
          this.model.setTimeNow( new Date() );
        this.model.setProducts( this.productManager.getProducts() );
        this.model.setProductTotal( this.productManager.getTotalCost() );   
        logger.debug( "**** Debugging Model:\n" + model );
         return new ModelAndView( "products", "model", model );
    }

Basically the prefix is added in front of “products” and the suffix is added at the end of “products”. This has the affect of decoupling the Controller from the view.

Difference 2: ModelAndView has 3 arguments. Look at the Controller:
public class SpringController implements Controller {    
        protected Logger logger = Logger.getLogger( SpringController.class );
        private Model model;
        private ProductManager productManager;
        public Model getModel() {
    return model;
    }
    public void setModel(Model model) {
        this.model = model;
    }
    public ProductManager getProductManager() {
        return productManager;
    } 
    public void setProductManager(ProductManager productManager) {
        this.productManager = productManager;
    } 
    public ModelAndView handleRequest(
            HttpServletRequest request, HttpServletResponse response )            
                throws ServletException, IOException {        
        this.model.setTimeNow( ( new Date() ).toString() );
            this.model.setProducts( this.productManager.getProducts() );
            this.model.setProductTotal( this.productManager.getTotalCost() );
            logger.debug( "**** Debugging Model:\n" + model );
               return new ModelAndView( "products", "model", model );
        }} 

You can see that the value of today’s date is assigned to the timeNow attributeof the model and passed to the View. The view in this case is /WEB-INF/jsp/products.jsp:

<%@ include file="/WEB-INF/jsp/include.jsp" %> 
<html>
 <head><title><fmt:message key="title"/></title></head>
 <body>
  <h1><fmt:message key="heading"/></h1>
  <p>
   <fmt:message key="time"/> <c:out value="${model.timeNow}"/>
  </p> 
  <h3><fmt:message key="products"/></h3>
  <table border="1" cellspacing="1" cellpadding="1">
  <c:forEach items="${model.products}" var="product">
   <tr bgcolor="lightgrey">
    <td>
     <c:out value="${product.description}"/>
    </td>
    <td>
     <c:out value="${product.price}"/>
    </td>
   </tr>
  </c:forEach>
   <tr bgcolor="antiquewhite">
    <td>
     Total
    </td>
    <td>
     <c:out value="${model.productTotal}"/> 
    </td>
   </tr> 
  </table>
  <br><br>
  <a href="<c:url value="priceincrease.spring"/>">Increase Prices</a>
 </body>
</html>

Notice that the value of “model.timeNow” is retrieved using the “out” tag library. Variables are retrieved using the $ and curly brackets. To see how maps to the Tag class look at include.jsp

<%@ page session=”false”%> 
<%@ taglib prefix=”c” uri=”http://java.sun.com/jstl/core” %> 
<%@ taglib prefix=”fmt” uri=”http://java.sun.com/jstl/fmt” %>

Notice that the tag, has been mapped to the library with the URL http://java.sun.com/jstl/core. Note that the URI could be a logical name that maps to the location of a tld file. JBoss decides whether the URI maps to a specific tld file or not as follows: JBoss looks in web.xml at the taglib entries for any tag libraries that have the URI “http://java.sun.com/jstl/core” or “http://java.sun.com/jstl/fmt”. JBoss then looks in the Classpath if it can find any tld files that match. The tld files in turn describe which java class to run for the tag.

products.jsp

products.jsp looks like:

<%@ include file="/WEB-INF/jsp/include.jsp" %> 
    <html>
        <head><title><fmt:message key="title"/></title></head>
        <body>
            <h1><fmt:message key="heading"/></h1>
            <p>
                <fmt:message key="time"/> <c:out value="${model.timeNow}"/>
            </p> 
            <h3><fmt:message key="products"/></h3>
            <table border="1" cellspacing="1" cellpadding="1">
                <c:forEach items="${model.products}" var="product">
                <tr bgcolor="lightgrey">
                        <td>
                            <c:out value="${product.description}"/>
                        </td>
                        <td>
                        <c:out value="${product.price}"/>
                        </td>
                </tr>
                </c:forEach>

<tr bgcolor="antiquewhite"> <td> Total </td> <td> <c:out value="${model.productTotal}"/> </td> </tr> </table> <br><br> <a href="<c:url value="priceincrease.spring"/>">Increase Prices</a> </body> </html>

Note that the jsp has some tag classes in it. The message tag, e.g. maps to a tag library whose definition is found in include.jsp. Include.jsp looks like:

<%@ page session="false"%> 
<%@ taglib prefix="c" uri=<A href="http://java.sun.com/jstl/core">http://java.sun.com/jstl/core</A>" %> <BR><%@ taglib prefix="fmt" uri="<A href="http://java.sun.com/jstl/core">http://java.sun.com/jstl/core</A>" %> 
<%@ taglib prefix="fmt" uri="<A href="http://java.sun.com/jstl/core">http://java.sun.com/jstl/core</A>" <%@ taglib prefix="fmt" uri="<a href="http://java.sun.com/jstl/fmt">http://java.sun.com/jstl/fmt</A>"" %>

The message tag looks in a property file to find its text. The property file is defined in the spring config file.

Conclusion

This tutorial has taken has through the basic steps that makes us familiar with the Spring Framework. Having gone through it, you are expected to have understood the basics of how the Spring Framework operates.

Need Web Hosting? Try ours, it's fast, reliable and feature loaded with support you can depend on. From £1.60 / month.

View Plans