Você está na página 1de 32

Spring Framework Lab book

Patni Computer Systems Ltd.

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

Working with Spring: ....................................................................................................................................................3

Lab 1-1: Injecting dependencies into a working application. ................................................................... 8

Lab 2-1: Injecting dependencies. ............................................................................................................... 14

Lab 3-1: Spring MVC.................................................................................................................................... 16

Lab 4-1: Hibernate with Spring AOP.......................................................................................................... 25

Lab 5-1: Integrating Struts with Spring. .................................................................................................... 26

Table of Examples: ...................................................................................................................................... 31

Table of Figures:.......................................................................................................................................... 32

Page 2 of 71
Copyright © 2006 by Patni
Spring Framework Lab book

Setup Checklist for Spring Framework


Setup
Here is what is expected on your machine in order for the lab assignments to work.

Minimum System Requirements

• Intel Pentium IV or higher


• Microsoft Windows (NT 4.0/XP/2K)
• Memory: 256MB of RAM (512 recommended)
• 500MB hard disk space
• JDK version 1.4 with help, Netscape or IE
• MS-Access/Connectivity to Oracle database
• Apache Tomcat Version 5.0
• Eclipse 3.1
Spring API. To download Spring, go to http://sourceforge.net/projects/springframework/ and
click "Download Spring Framework". This will bring you to the download page. We want the latest version
of Spring with all its dependencies; at the time of this writing it's spring-framework-1.2.7-with-
dependencies.zip. Download it and unzip it.

Please ensure that the following is done:

1. JDK 1.4 and Eclipse are installed


2. Apache Tomcat is installed but not started

Working with Spring:


The easiest way to begin working with Spring using Eclipse would be to first create a folder with all the
source files. For example see the figure below for contents of a typical folder:

Page 3 of 71
Copyright © 2006 by Patni
Spring Framework Lab book

Figure 1.1 : A typical Spring with Eclipse folder

Next, from within Eclipse, create a new Java project, and give a name say SpringProj and set the source
for the project contents.

Figure 1.2 : Step 1 - Creating new Project in Eclipse

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

Figure 1.3 : Step 2 – Bringing in jars to the project

At this stage the project should look like the figure below:

Page 5 of 71
Copyright © 2006 by Patni
Spring Framework Lab book

Figure 1.4 : The project in Eclipse

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

Figure 1.5 : Spring web-based application –Folder structure

Page 7 of 71
Copyright © 2006 by Patni
Spring Framework Lab book

Lab 1-1: Injecting dependencies into a working


application.
Goals Using IoC to integrate disparate systems in a loosely coupled manner.

Time 60 minutes

Lab Setup ƒ Spring framework with all its dependency files.


ƒ Eclipse editor

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 {

public boolean getUserCreditHistoryInformation(ICustomer iCustomer);

Example 1.1.1 : CreditRatingInterface.java

// To do : Implement the CreditRating interface in a CreditRating class that simply returns true

package springexample.creditlinking;
public interface CreditLinkingInterface {

public String getUrl();


public void setUrl(String url);
public void linkCreditBankAccount() throws Exception ;

Example 1.1.2 : CreditLinkingInterface.java

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

public void linkCreditBankAccount(ICustomer icustomer) throws Exception {


//Connect to URL
System.out.println("url to connect is" + url);

System.out.println("credit card linked for customer id " +icustomer.getCustomerId());


}

//To do : implement setter and getters for url property.


}

Example 1.1.3 : CreditLinking.java

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;

public interface EmailInterface {

public void sendEmail(ICustomer iCustomer);


public String getFromEmail();
public void setFromEmail(String fromEmail) ;
public String getPassword();
public void setPassword(String password) ;
public String getSmtpHost() ;
public void setSmtpHost(String smtpHost);
public String getUserId() ;
public void setUserId(String userId);
}

Example 1.1.4 : EmailInterface.java

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.

//To do : implement the Email class

Other classes/interfaces in this application:

package springexample.domain;

public interface IAddress {

public String getAddress1() ;


public void setAddress1(String address1) ;
public String getAddress2();
public void setAddress2(String address2);
public String getCity() ;
public void setCity(String city);

Page 9 of 71
Copyright © 2006 by Patni
Spring Framework Lab book

public String getCountry() ;


public void setCountry(String country);
public String getState();
public void setState(String state) ;
public String getZipCode() ;
public void setZipCode(String zipCode) ;

Example 1.1.5 : IAddress.java

// To do :Code the Address class that implements the IAddress interface

package springexample.domain;

//Interface holds customer information.


public interface ICustomer {
public String getCustomerId();
public void setCustomerId(String customerId);
public String getFirstName();
public void setFirstName(String firstName);
public IAddress getIAddress();
public void setIAddress(IAddress address);
public String getLastName();
public void setLastName(String lastName);
public String getSsnId();
public void setSsnId(String ssnId);
public String getEmailAddress();
public void setEmailAddress(String emailAddress);
public boolean isCreditRating() ;
public void setCreditRating(boolean creditRating);

Example 1.1.6 : Icustomer.java

// To do :Code the Customer class that implements the Icustomer interface

package springexample.creditcardaccount;

import springexample.creditlinking.CreditLinkingInterface;
import springexample.creditrating.CreditRatingInterface;
import springexample.domain.ICustomer;
import springexample.email.EmailInterface;

public interface CreateCreditCardAccountInterface {

public CreditLinkingInterface getCreditLinkingInterface();


public void setCreditLinkingInterface(
CreditLinkingInterface creditLinkingInterface);
public CreditRatingInterface getCreditRatingInterface();
public void setCreditRatingInterface(
CreditRatingInterface creditRatingInterface);

Page 10 of 71
Copyright © 2006 by Patni
Spring Framework Lab book

public EmailInterface getEmailInterface();


public void setEmailInterface(EmailInterface emailInterface);
public void createCreditCardAccount(ICustomer icustomer) throws Exception;

Example 1.1.7: CreateCreditCardAccountInterface.java

// To do :Code the CreateCreditCardAccount class that implements the


CreateCreditCardAccountInterface interface

public void createCreditCardAccount(ICustomer icustomer) throws Exception{


boolean crediRating = getCreditRatingInterface().getUserCreditHistoryInformation(icustomer);
icustomer.setCreditRating(crediRating);
//Good Rating
if(crediRating){
getCreditLinkingInterface().linkCreditBankAccount(icustomer);
}

Example 1.1.8: part of CreateCreditCardAccount.java

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;

public class CreateCreditAccountClient {

public static void main(String[] args){


try
{
System.out.println("CreateCreditAccountClient started");

// To do : load the configuration file (springexample-creditaccount.xml) file into the container

//To Do : Create a customer object and invoke setter methods to populate

//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

Example 1.1.9 : CreateCreditAccountClient.java

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-


beans.dtd">

<beans>

<bean id="createCreditCard" class="springexample.creditcardaccount.CreateCreditCardAccount">


<property name="creditRatingInterface">
<ref bean="creditRating" />
</property>
<property name="creditLinkingInterface">
<ref bean="creditLinking" />
</property>
<property name="emailInterface">
<ref bean="email" />
</property>
</bean>

<bean id="creditLinking" class="springexample.creditlinking.CreditLinking">


<property name="url">
<value>http://localhost/creditLinkService</value>
</property>
</bean>

<bean id="creditRating" class="springexample.creditrating.CreditRating">


</bean>

<bean id="email" class="springexample.email.Email">


<property name="smtpHost">
<value>localhost</value>
</property>
<property name="fromEmail">
<value>mycompanyadmin@mycompanyadmin.com</value>
</property>
<property name="userId">
<value>myuserid</value>
</property>
<property name="password">
<value>mypassword</value>
</property>
</bean>

</beans>

Example 1.1.10 : The configuration file - springexample-creditaccount.xml

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

CreateCreditAccountClient will also load the Spring configuration files through


ClassPathXmlApplicationContext. Once the beans are loaded, you can then access them through the
getBean() method, in above CreateCreditAccountClient class.

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

Lab 2-1: Injecting dependencies.


Goals Using IoC to integrate disparate systems in a loosely coupled manner.

Time 60 minutes

Lab Setup ƒ Spring framework with all its dependency files.


ƒ Eclipse editor

Please refer to the configuration file below:

<?xml version="1.0" encoding="UTF-8"?>


<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-
beans.dtd">
<beans>
<bean class="library.BookDetails.BookList" id="BookList">
<property name="books">
<list>
<ref bean="JStruts"/>
<ref bean="Unix"/>
<ref bean="SpringFramework"/>
</list>
</property>
</bean>

<bean id="JStruts" class="library.BookDetails.Book">


<property name="title">
<value>Jakarta Struts</value>
</property>
<property name="author">
<value>Chuck Cavaness</value>
</property>
<property name="pubHouse">
<value>O'Reilly</value>
</property>
<property name="price">
<value>250</value>
</property>
</bean>

<bean id="Unix" class="library.BookDetails.Book">


<property name="title">
<value>Unix for Users</value>
</property>
<property name="author">
<value>Yashwanth Kanetkar</value>
</property>
<property name="pubHouse">
<value>Sybase publications</value>
</property>
<property name="price">
<value>175</value>
</property>

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:

"Jakarta Struts" by Chuck Cavaness:


Publishing House : O'Reilly
Price : Rs 250

"Unix for Users" by Yashwanth Kanetkar:


Publishing House : Sybase publications
Price : Rs 175

"Spring in Action" by Craig Walls :


Publishing House : Manning publications
Price : Rs 350

Figure 2.1 : Output for the Book Application

Page 15 of 71
Copyright © 2006 by Patni
Spring Framework Lab book

Lab 3-1: Spring MVC


Goals Demonstrate Spring's MVC framework.

Time 60 Minutes

Lab Setup ƒ Apache Tomcat 5.0 +


ƒ Spring.jar

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.

<?xml version="1.0" encoding="ISO-8859-1"?>

<!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>

Example 3.1.1 : web.xml for Spring MVC framework

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:

Figure 3.1.1 : Login.jsp

Page 17 of 71
Copyright © 2006 by Patni
Spring Framework Lab book

Figure 3.1.2 : accountdetails.jsp

The LoginBankController extends Spring MVC's SimpleFormController. LoginBankController uses


AuthenticationService and AccountServices services for authentication and carrying out account
activities. The AuthenticationService class handles authentication for the banking application. The
AccountServices class handles typical banking services such as viewing transactions and wire transfers.

package springexample.services;
import springexample.commands.LoginCommand;

public class AuthenticationService {


public AuthenticationService(){
}

public void authenticate(LoginCommand command) throws Exception{


//To do : Check with some dummy data and if authentication successful

System.out.println("Login sucessful");
}else{
throw new Exception("User id is not authenticated");
}
}
}

Example 3.1.2 : AuthenticationService.java

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 class AccountServices {

public AccountServices(){
}

public AccountDetail getAccountSummary(String userId){

//Return some dummy data


AccountDetail accountDetail = new AccountDetail();

//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>);

//To do : Create User object and populate using setter methods.


return accountDetail;
}
}

Example 3.1.3 : AccountServices.java

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 class LoginBankController extends SimpleFormController {

public LoginBankController(){
}

protected ModelAndView onSubmit(Object command) throws Exception{

LoginCommand loginCommand = (LoginCommand) command;


authenticationService.authenticate(loginCommand);
AccountDetail accountdetail =
accountServices.getAccountSummary(loginCommand.getUserId());
return new ModelAndView(getSuccessView(),"accountdetail",accountdetail);
}

private AuthenticationService authenticationService;

private AccountServices accountServices;

Page 19 of 71
Copyright © 2006 by Patni
Spring Framework Lab book

//To do : implement setters and getters for authentication and accounts service
}

Example 3.1.4 : LoginBankController.java

Mapping requests to controllers: The next listing (3.1.5) shows the controller configuration.

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-


beans.dtd">

<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.
Æ

<bean id="loginBankController" class="springexample.contoller.LoginBankController">


<property name="sessionForm"><value>true</value></property>
<property name="commandName"><value>loginCommand</value></property>
<property name="commandClass"> <value>springexample.commands.LoginCommand</value>
</property>

<!-- wire AuthenticationService and AccountServices to 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>

<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>/jsp/</value></property>
<property name ="suffix"><value>.jsp</value></property>
</bean>

</beans>

Example 3.1.5 : sampleBankingServlet-servlet.xml

Finally, we need to configure the banking application's authentication and account services.

<?xml version="1.0" encoding="UTF-8"?>


<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-
beans.dtd">

<beans>
<bean id="accountServices" class="springexample.services.AccountServices">
</bean>

<bean id="authenticationService" class="springexample.services.AuthenticationService">


</bean>
</beans>

Example 3.1.6 : sampleBanking-services.xml

Other classes in the application:

package springexample.commands;
import java.math.BigDecimal;
public class Account {

private String accountName;


private String accountType;
private BigDecimal accountbalance;
private String accountNumber;

//To do : implement all the setter/getter methods for the above properties.
}

Example 3.1.7 : Account.java

package springexample.commands;

Page 21 of 71
Copyright © 2006 by Patni
Spring Framework Lab book

public class LoginCommand {

public LoginCommand(){
}

private String userId;


private String password;

//To do : implement all the setter/getter methods for the above properties.

Example 3.1.8 : LoginCommand.java

package springexample.commands;

import java.util.List;

public class AccountDetail {

private List accountsList;


private User user;

//To do : implement all the setter/getter methods for the above properties.

Example 3.1.9 : AccountDetail.java

package springexample.commands;

public class User {

private String userId;


private String firstName;
private String lastName;
//Address and so on.

//To do : implement all the setter/getter methods for the above properties.

Example 3.1.10 : User.java

<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>


<%@ taglib prefix="spring" uri="/spring" %>

<html><head>
<title>Login to Spring Example Account Banking</title></head>

<body>

<h1>Please enter your userid and password.</h1>

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>

<table width="95%" bgcolor="f8f8ff" border="0" cellspacing="0" cellpadding="5">


<tr>
<td alignment="right" width="20%">User id:</td>
<spring:bind path="loginCommand.userId">
<td width="20%">
<input type="text" name="<c:out value="${status.expression}"/>" value="<c:out
value="${status.value}"/>">
</td>
</spring:bind>
<td width="60%">
</tr>

<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>

Example 3.1.11 : login.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>


<%@ taglib prefix="spring" uri="/spring" %>

<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>

<table width="95%" bgcolor="f8f8ff" border="0" cellspacing="0" cellpadding="5">


Following are the list of your accounts and its details.
<c:forEach items="${accountdetail.accountsList}" var ="accountsList">
<tr>
<td alignment="right" width="20%">Account Name: <c:out value ="${accountsList.accountName}"/></td>
<td alignment="right" width="20%">Account Type: <c:out value ="${accountsList.accountType}"/></td>
<td alignment="left" width="20%">Account Number: <c:out value
="${accountsList.accountNumber}"/></td>
<td alignment="right" width="20%">Account Balance: <c:out value
="${accountsList.accountbalance}"/></td>
<td width="60%">
</tr>
<tr>
</tr>
</c:forEach>
</table>
<br/>
<a href="/springbanking/jsp/login.obj">logout</a>
</body>
</html>

Example 3.1.12 : accountdetail.jsp


Run the application by invoking the login.jsp as:

http://localhost:8080/springbanking/jsp/login.obj

Page 24 of 71
Copyright © 2006 by Patni
Spring Framework Lab book

Lab 4-1: Hibernate with Spring AOP.


Goals Demonstrate Spring's persistence support.

Time 90 Minutes

Lab Setup ƒ Appropriate jars (spring and Hibernate)


ƒ Oracle database
ƒ Tomcat server 5.0 +

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

Lab 5-1: Integrating Struts with Spring.


(Optional)

Goals Struts with Spring integration.

Time 120 Minutes

Lab Setup Appropriate jars (spring and Hibernate)


Oracle database
Tomcat server 5.0 +

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:

The application makes use of two tables:

SQL> desc bankmaster;


Name Null? Type
----------------------------------------- -------- --------------
BANKCODE VARCHAR2(5)
BANKNAME VARCHAR2(15)
ACCOUNTNUMBER VARCHAR2(10)
CURRENTBALANCE NUMBER(7,2)

SQL> desc banktransactions;


Name Null? Type
----------------------------------------- -------- ------------------------
BANKCODE VARCHAR2(5)
SRNO NUMBER(4)
AMOUNT NUMBER(9,2)
TYPE VARCHAR2(8)
RUNNINGBALANCE NUMBER(9,2)
PARTY VARCHAR2(10)
NARRATION VARCHAR2(20)
DRAWNON DATE
CHEQUENUMBER NUMBER(10)

Page 26 of 71
Copyright © 2006 by Patni
Spring Framework Lab book

Figure 5.1.1 : Main.jsp

The buttons perform the following tasks:


ƒ Add : Add a new bank.
ƒ Edit : Edit bank details.
ƒ Transactions : Edit transactions.
ƒ Delete : delete a bank.
ƒ Print : (not shown in figure) To print transactions.

When user clicks on “add”, the following form (figure 5.1.2) appears:

Figure 5.1.2 : Add new bank details.

Page 27 of 71
Copyright © 2006 by Patni
Spring Framework Lab book

The data is accepted as per the following rules:

BankCode Text, mandatory, upto 4 characters, Bankcode must be unique


BankName Text, mandatory, upto 15 characters
AccountNumber Text, mandatory, upto 10 characters

Clicking on Save must show the following screen (figure 5.1.3):

Figure 5.1.3 : New bank added details.

Clicking on the “edit” must display the following screen:

Page 28 of 71
Copyright © 2006 by Patni
Spring Framework Lab book

Figure 5.1.4 : Editing bank.

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.

Figure 5.1.5: Editing transaction

Code for all the buttons on this form.

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

Você também pode gostar