Escolar Documentos
Profissional Documentos
Cultura Documentos
Spring Framework
Lab Guide
Version – 0.01 d
25-July-2006
Copyright © 2004 Patni Computer Systems., Akruti, MIDC Cross Road No. 21, Andheri (E), Mumbai 400
093. All rights reserved. No part of this publication reproduced in any way, including but not limited to
photocopy, photographic, magnetic, or other record, without the prior agreement and written
permission of Patni Computer Systems.
Patni Computer Systems, considers information included in this document to be Confidential and
Proprietary.
Page 1 of 71
Copyright © 2006 by Patni
Spring Framework Lab book
Table of Contents
Setup Checklist for Spring Framework ....................................................................................................... 3
Setup ................................................................................................................................................................................3
Table of Figures:.......................................................................................................................................... 32
Page 2 of 71
Copyright © 2006 by Patni
Spring Framework Lab book
Page 3 of 71
Copyright © 2006 by Patni
Spring Framework Lab book
Next, from within Eclipse, create a new Java project, and give a name say SpringProj and set the source
for the project contents.
In the library tab, choose external jars and bring in all the jars that exist in the lib folder that we
created above.
Page 4 of 71
Copyright © 2006 by Patni
Spring Framework Lab book
At this stage the project should look like the figure below:
Page 5 of 71
Copyright © 2006 by Patni
Spring Framework Lab book
To run web-based Spring application, simply create a folder under webapps and bring the appropriate
jars into the lib folder. The figure below shows the structure of a typical web application:
Page 6 of 71
Copyright © 2006 by Patni
Spring Framework Lab book
Page 7 of 71
Copyright © 2006 by Patni
Spring Framework Lab book
Time 60 minutes
Let us take the case of opening an online credit card account. With respect to the implementation,
opening a credit card account requires that the user interact with the following services:
A credit rating service that queries the user's credit history information
A remote credit linking service that inserts and links customer information with credit card and
bank information for the purpose of automatic debits (if required)
An e-mail service that e-mails the user about the status of his credit card
For this example, we will assume that the services already exist and that it is desirable to integrate
them in a loosely coupled manner. The listings below show the application interfaces for the three
services.
package springexample.creditrating;
public interface CreditRatingInterface {
// To do : Implement the CreditRating interface in a CreditRating class that simply returns true
package springexample.creditlinking;
public interface CreditLinkingInterface {
package springexample.creditlinking;
import springexample.domain.ICustomer;
public class CreditLinking implements CreditLinkingInterface {
private String url;
Page 8 of 71
Copyright © 2006 by Patni
Spring Framework Lab book
The credit linking interface links credit history information with bank information (if required), and
inserts credit card information for the user. The credit linking interface is a remote service whose lookup
is made through the getUrl() method. The URL is set by the Spring framework's beans configuration
mechanism, which is given in example 1.1.4 below. The implementation is provided by the CreditLinking
class.
package springexample.email;
import springexample.domain.ICustomer;
The EmailInterface is responsible for sending e-mail to the customer regarding the status of his or her
credit card. Mail configuration parameters such as SMPT host, user, and password are set by the
previously mentioned beans configuration mechanism. The Email class provides the implementation.
package springexample.domain;
Page 9 of 71
Copyright © 2006 by Patni
Spring Framework Lab book
package springexample.domain;
package springexample.creditcardaccount;
import springexample.creditlinking.CreditLinkingInterface;
import springexample.creditrating.CreditRatingInterface;
import springexample.domain.ICustomer;
import springexample.email.EmailInterface;
Page 10 of 71
Copyright © 2006 by Patni
Spring Framework Lab book
With all the interfaces in place, the next thing to consider is how to integrate them in a loosely coupled
manner. In below listing you can see the implementation of the credit card account use case.
package springexample.client;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import springexample.creditcardaccount.CreateCreditCardAccountInterface;
import springexample.domain.Customer;
import springexample.domain.ICustomer;
//To do : call the getBean() method on the BeanFactory to retrieve a reference to the
createCreditCard service
//To do : invoke the createCreditCardAccount() by providing the customer object created above
}
catch(Exception e){
e.printStackTrace();
}
}
Page 11 of 71
Copyright © 2006 by Patni
Spring Framework Lab book
<beans>
</beans>
Run the CreateCreditAccountClient class, which in turn will create a Customer class object and populate
it and also call the CreateCreditCardAccount class to create and link the credit card account. The
Page 12 of 71
Copyright © 2006 by Patni
Spring Framework Lab book
In this example you saw how simple it was to inject dependencies, or services, into a working credit card
account application rather than having to build them in from the ground up.
Page 13 of 71
Copyright © 2006 by Patni
Spring Framework Lab book
Time 60 minutes
Page 14 of 71
Copyright © 2006 by Patni
Spring Framework Lab book
</bean>
<bean id="SpringFramework" class="library.BookDetails.Book">
<property name="title">
<value>Spring in Action</value>
</property>
<property name="author">
<value>Craig Walls </value>
</property>
<property name="pubHouse">
<value>Manning publications</value>
</property>
<property name="price">
<value>350</value>
</property>
</bean>
</beans>
This is a very simple example of a BookStore application. The configuration file contains details of books.
Please code the relevant classes based on the bean attributes. Code the main class to bring all the
classes together, so that the output looks like the figure below:
Page 15 of 71
Copyright © 2006 by Patni
Spring Framework Lab book
Time 60 Minutes
This banking application will allow users to retrieve their account information. You'll learn how to
configure the Spring MVC framework and implement the framework's view layer, which will consist of
JavaServer Pages technology with JSTL tags for rendering the output data. To start building the example
application, configure Spring MVC's DispatcherServlet. Register all configurations in your web.xml file.
Listing 3.1.1 shows how to configure the sampleBankingServlet.
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<!—
The DispatcherServlet loads a Spring application context from the XML file whose name is based on the
name of the servlet, with -servlet appended to it. In this case, the DispatcherServlet will load its
application context from the sampleBankingServlet-servlet.xml file.
Æ
<servlet>
<servlet-name>sampleBankingServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<!—
The next step is to configure the URLs that you want the sampleBankingServlet to handle. Again, you will
register these configurations in the web.xml file.
Æ
<servlet-mapping>
<servlet-name>sampleBankingServlet</servlet-name>
<url-pattern>*.obj</url-pattern>
</servlet-mapping>
<!—
Next, load the configuration files. To do this, register the ContextLoaderListener for Servlet 2.3
specifications or ContextLoaderServlet for Servlet 2.2 containers and below. Use ContextLoaderServlet
for backward compatibility. The ContextLoaderServlet will load the Spring configuration files when you
start the Web application. Listing 3 registers the ContextLoaderServlet
Æ
Page 16 of 71
Copyright © 2006 by Patni
Spring Framework Lab book
<servlet>
<servlet-name>context</servlet-name>
<servlet-class>org.springframework.web.context.ContextLoaderServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<!—
The contextConfigLocation parameter defines the Spring configurations files to load, as shown in the
servlet context below. To load multiple Spring configuration files, use a comma as a delimiter in a
<param-value> tag.
Æ
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/sampleBanking-services.xml</param-value>
</context-param>
<taglib>
<taglib-uri>/spring</taglib-uri>
<taglib-location>/WEB-INF/spring.tld</taglib-location>
</taglib>
</web-app>
The example banking application allows users to view account information based on a unique ID and
password, using JSP technology for view pages. This simple application will consist of one view page for
user input (ID and password) and a second page to display the user's account information as seen in the
figures below:
Page 17 of 71
Copyright © 2006 by Patni
Spring Framework Lab book
package springexample.services;
import springexample.commands.LoginCommand;
System.out.println("Login sucessful");
}else{
throw new Exception("User id is not authenticated");
}
}
}
package springexample.services;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
Page 18 of 71
Copyright © 2006 by Patni
Spring Framework Lab book
import springexample.commands.Account;
import springexample.commands.AccountDetail;
import springexample.commands.User;
public AccountServices(){
}
//To do : Create two Account objects and populate using setter methods.
// To do : Create List collection object and add Account objects.
accountDetail.setAccountsList(<list object>);
package springexample.contoller;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import springexample.commands.AccountDetail;
import springexample.commands.LoginCommand;
import springexample.services.AccountServices;
import springexample.services.AuthenticationService;
public LoginBankController(){
}
Page 19 of 71
Copyright © 2006 by Patni
Spring Framework Lab book
//To do : implement setters and getters for authentication and accounts service
}
Mapping requests to controllers: The next listing (3.1.5) shows the controller configuration.
<beans>
<bean id="simpleUrlMapping" class =
"org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name ="mappings">
<props>
<prop key ="/login.html">loginBankController</prop>
</props>
</property>
</bean>
<!—
The commandClass and commandName tags determine the bean that will be active in the view page. For
example, the loginCommand bean will be accessible through login.jsp, which is the application's login
page. Once the user submits the login page, the application can retrieve the form data from the
command object in the onSubmit() method of the LoginBankController.
Æ
<property name="authenticationService">
<ref bean="authenticationService" />
</property>
<property name="accountServices">
<ref bean="accountServices" />
</property>
<!-- register the page that displays on receipt of the HTTP GET request, using the formView property
-- >
<property name="formView">
<value>login</value>
</property>
<!—
The sucessView property represents the page which displays after form data is posted and logic is
successfully executed in the doSubmitAction() method. Both the formView and sucessView properties
represent the logical name of the view defined, which maps to the actual view page.
Æ
Page 20 of 71
Copyright © 2006 by Patni
Spring Framework Lab book
<property name="successView">
<value>accountdetail</value>
</property>
</bean>
</beans>
Finally, we need to configure the banking application's authentication and account services.
<beans>
<bean id="accountServices" class="springexample.services.AccountServices">
</bean>
package springexample.commands;
import java.math.BigDecimal;
public class Account {
//To do : implement all the setter/getter methods for the above properties.
}
package springexample.commands;
Page 21 of 71
Copyright © 2006 by Patni
Spring Framework Lab book
public LoginCommand(){
}
//To do : implement all the setter/getter methods for the above properties.
package springexample.commands;
import java.util.List;
//To do : implement all the setter/getter methods for the above properties.
package springexample.commands;
//To do : implement all the setter/getter methods for the above properties.
<html><head>
<title>Login to Spring Example Account Banking</title></head>
<body>
Page 22 of 71
Copyright © 2006 by Patni
Spring Framework Lab book
<p><form method="post">
<spring:bind path="loginCommand">
<c:forEach items="${status.errorMessage}" var ="errorMessage">
<font color="red">
<c:out value ="${errorMessage}"/><br>
</font>
</c:forEach>
</spring:bind>
<tr>
<td alignment="right" width="20%">Password:</td>
<spring:bind path="loginCommand.password">
<td width="20%">
<input type="password" name="<c:out value="${status.expression}"/>" value="<c:out
value="${status.value}"/>">
</spring:bind>
</td>
<td width="60%">
</tr>
</table>
<br>
<br>
<input type="submit" alignment="center" value="login">
</form>
</p>
</body>
</html>
<html><head>
<title>Login to Spring Example Account Banking</title></head>
Page 23 of 71
Copyright © 2006 by Patni
Spring Framework Lab book
<body>
<h1>Account Details</h1>
<p><form method="post">
<spring:bind path="accountdetail">
<c:forEach items="${status.errorMessage}" var ="errorMessage">
<font color="red">
<c:out value ="${errorMessage}"/><br>
</font>
</c:forEach>
</spring:bind>
http://localhost:8080/springbanking/jsp/login.obj
Page 24 of 71
Copyright © 2006 by Patni
Spring Framework Lab book
Time 90 Minutes
Implement the authentication service and account service in the previous (lab 3-1) banking example
using persistence support.
The authentication service would use a database to authenticate users. The accounts service would use a
database to retrieve a user’s account details.
Page 25 of 71
Copyright © 2006 by Patni
Spring Framework Lab book
This example builds on the example 15 seen in the class sessions, the code for which can be found in the
classbook in appendix B. This is an application for managing bank accounts and its transactions. When
the system is started, the main window is displayed as shown in figure 5.1.1 below:
Page 26 of 71
Copyright © 2006 by Patni
Spring Framework Lab book
When user clicks on “add”, the following form (figure 5.1.2) appears:
Page 27 of 71
Copyright © 2006 by Patni
Spring Framework Lab book
Page 28 of 71
Copyright © 2006 by Patni
Spring Framework Lab book
Editing transactions: When user select a bank entry in the main window and selects “transactions”, a
list of all transactions for that bank are displayed. Data is sorted by transaction date + serial number
(must be a system generated field, hidden from user).
The following buttons must be displayed in shown in figure below:
New transaction.
Edit transaction.
Delete transaction.
Print transactions.
New transaction : When user chooses “new transaction”, following validations must be in place:
date Mandatory
amount Number, mandatory, cannot be zero, positive amount means deposit, negative
means withdraw.
party Text upto 40 characters, mandatory
Cheque drawn on To be accepted only if it is a deposit type of transaction, Optional
Editing a transaction: A user may select a transaction from the transaction list and edit its details. Date
fiels cannot be changed in edit mode. If amount changes, then the “runningBalance” field fro that
transaction as well as the following transactions are updated.
Page 29 of 71
Copyright © 2006 by Patni
Spring Framework Lab book
Deleting a transaction : An user may delete a transaction. The system must confirm with the user and
then delete the record. Running balances for all transactions after that record will be updated.
Printing statement: If a user chooses to print transactions, the system must print the statement of
transactions for that bank. Format for this is left to the participants.
Page 30 of 71
Copyright © 2006 by Patni
Spring Framework Lab book
Table of Examples:
Example 1.1.1 : CreditRatingInterface.java .......................................................................... 8
Example 1.1.2 : CreditLinkingInterface.java ......................................................................... 8
Example 1.1.3 : CreditLinking.java .................................................................................... 9
Example 1.1.4 : EmailInterface.java................................................................................... 9
Example 1.1.5 : IAddress.java ......................................................................................... 10
// To do :Code the Address class that implements the IAddress interface .................................. 10
Example 1.1.6 : Icustomer.java ....................................................................................... 10
// To do :Code the Customer class that implements the Icustomer interface.............................. 10
Example 1.1.7: CreateCreditCardAccountInterface.java .......................................................... 11
Example 1.1.8: part of CreateCreditCardAccount.java ............................................................ 11
Example 1.1.9 : CreateCreditAccountClient.java................................................................... 12
Example 1.1.10 : The configuration file - springexample-creditaccount.xml .................................. 12
Example 3.1.1 : web.xml for Spring MVC framework .............................................................. 17
Example 3.1.2 : AuthenticationService.java ........................................................................ 18
Example 3.1.3 : AccountServices.java................................................................................ 19
Example 3.1.4 : LoginBankController.java........................................................................... 20
Example 3.1.5 : sampleBankingServlet-servlet.xml ................................................................ 21
Example 3.1.6 : sampleBanking-services.xml ....................................................................... 21
Example 3.1.7 : Account.java.......................................................................................... 21
Example 3.1.8 : LoginCommand.java ................................................................................. 22
Example 3.1.9 : AccountDetail.java .................................................................................. 22
Example 3.1.10 : User.java............................................................................................. 22
Example 3.1.11 : login.jsp.............................................................................................. 23
Example 3.1.12 : accountdetail.jsp ................................................................................... 24
Page 31 of 71
Copyright © 2006 by Patni
Spring Framework Lab book
Table of Figures:
Figure 1.1 : A typical Spring with Eclipse folder ..................................................................... 4
Figure 1.2 : Step 1 - Creating new Project in Eclipse ............................................................... 4
Figure 1.3 : Step 2 – Bringing in jars to the project ................................................................. 5
Figure 1.4 : The project in Eclipse ..................................................................................... 6
Figure 1.5 : Spring web-based application –Folder structure ...................................................... 7
Figure 3.1.1 : Login.jsp ................................................................................................. 17
Figure 3.1.2 : accountdetails.jsp ...................................................................................... 18
Figure 5.1.1 : Main.jsp .................................................................................................. 27
Figure 5.1.2 : Add new bank details. ................................................................................. 27
Figure 5.1.3 : New bank added details. .............................................................................. 28
Figure 5.1.4 : Editing bank. ............................................................................................ 29
Figure 5.1.5: Editing transaction ..................................................................................... 29
Page 32 of 71
Copyright © 2006 by Patni