1. 这是4个Servlet之间的通信
2. 代码如下:
1) 首先是test.htm文件,它作为客户端访问的页面
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML><HEAD>
<META http-equiv=Content-Type content="text/html; charset=gb2312">
<META content="Microsoft FrontPage 4.0" name=GENERATOR></HEAD>
<BODY>
<CENTER>
<H1>Earnest Bank </H1></CENTER>
<FORM action="http://127.0.0.1:8000/servlet/firstservlet" method=post>enter your account Number here <INPUT name=accnum size="21">
<BR><BR><BR>enter your pin Number here <INPUT name=pinnum size="21"> <BR>
<p>
<CENTER><INPUT type=submit value=submit></CENTER></p>
</FORM></BODY></HTML>
2) 第一个Servelt代码:(作用是检验用户输入account Number 和pin Number是否合法)
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;
///import javax.sql.*;
public class FirstServlet extends HttpServlet
{
static Connection dbcon;
static String resultToSecond="NA";
protected void doPost(HttpServletRequest req,
HttpServletResponse resp)
throws ServletException,
java.io.IOException
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
dbcon=DriverManager.getConnection("jdbc:odbc:test","sa","");
System.out.println("Connection established");
}
catch(Exception e)
{
System.out.println("Database not found!");
}
//Create a share attribute创建一个共享属性
ServletContext context=this.getServletContext();
context.setAttribute("accountNumber","");
//得到从客户端发送过来的两个值
String accnum=req.getParameter("accnum");
String pinnum=req.getParameter("pinnum");
//Check whether the accountnum and pinnum are valid
try
{
PreparedStatement stat=dbcon.prepareStatement(
"select * from Login where cAccount_id=? and cPin_no=?");
stat.setString(1,accnum);
stat.setString(2,pinnum);
ResultSet result=stat.executeQuery();
if(result.next())
{
resultToSecond=result.getString(1);
context.setAttribute("accountNumber",resultToSecond);
//the account i valid call the second servlet通过验证后使用RequestDispatcher接口
//得到以URL为参数的Servlet的引用
RequestDispatcher dispatcher=context.getRequestDispatcher("/secondservlet");
if(dispatcher==null)
{
resp.sendError(resp.SC_NO_CONTENT);
}
//把请求提交或者委派给第二个Servlet
dispatcher.forward(req,resp);
try
{
dbcon.close();
}
catch(Exception e)
{
System.out.println(e.toString());
}
}
else
{
resp.setContentType("text/html");
PrintWriter out=resp.getWriter();
out.println("<html><body bgcolor=pink>");
out.println(" The account is invalid");
out.println("<br><br>");
out.println("</body></html>");
resultToSecond="NA";
out.close();
}
}
catch(Exception e){System.out.println(e);}
}
}
3) 第二个Servelt代码:(作用是显示Account Number,并允许用户输入Cheque number和支票金额amount)
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;
///import javax.sql.*;
//通过用getAttribute()函数得到帐号,显示用户账单号。点击deposit按钮,调用第三个Servlet
public class SecondServlet extends HttpServlet
{
Connection dbcon;
public void service(ServletRequest req,ServletResponse resp)
throws ServletException,java.io.IOException
{
resp.setContentType("text/html");
PrintWriter out=resp.getWriter();
//Accessing the account number from the servlet context
ServletContext context=this.getServletContext();
String value=(String)context.getAttribute("accountNumber");
out.println("<html><head>");
out.println("<META http-equiv=Content-Type content=\"text/html; charset=gb2312\">");
out.println("<META content=\"MSHTML 6.00.2600.0\" name=GENERATOR></HEAD>");
out.println("<body><CENTER><H1>Earnest Bank </H1></CENTER>");
out.println("<form action=http://127.0.0.1:8000/servlet/thirdservlet method=post>");
out.println("<b>Click the deposit button to deposit your money</b>");
out.println("<table>");
out.println("<tr><td>Account number: </td><td>"+value+"</td></tr>");
out.println("<tr><td>Cheque number: </td><td><input type=text name=checknum></td></tr>");
out.println("<tr><td>Enter the amount to be deposited: </td><td><input type=text name=amount value=0></td></tr>");
out.println("</table>");
out.println("<input type=submit value=deposit>");
out.println("<BR></form>");
out.println("</body></html>");
}
}
4) 第三个Servelt代码:(作用是显示数据插入成功,并允于用户查看交易报告)
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;
///import javax.sql.*;
public class ThirdServlet extends HttpServlet
{
Connection dbcon;
String accountNumber;
protected void doPost(HttpServletRequest req,
HttpServletResponse resp)
throws ServletException,
java.io.IOException
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
dbcon=DriverManager.getConnection("jdbc:odbc:test","sa","");
System.out.println("Connection established");
}
catch(Exception e)
{
System.out.println("Database not found!");
}
//Accessing the account number from the servlet context
ServletContext context=this.getServletContext();
String accnum=(String)context.getAttribute("accountNumber");
resp.setContentType("text/html");
PrintWriter out=resp.getWriter();
String amount=req.getParameter("amount");
String checknum=req.getParameter("checknum");
out.println("<html><body bgcolor=pink>");
boolean checkcorrect=true;
boolean amountcorrect=true;
if(checknum.length()==0)
{
checkcorrect=false;
out.println("Pls enter the cheque number properly");
}
double mdeposit=Double.parseDouble(amount);
if(mdeposit<=0)
{
amountcorrect=false;
out.println("The deposit amount must be valid");
out.println("<br>Pls reenter the amount");
}
if(checkcorrect && amountcorrect)
{
try
{
PreparedStatement stat=dbcon.prepareStatement(
"insert Account_Holder_Transaction values(?,getDate(),?,?,?)");
String vcparticulars=new String("Cheque Deposit");
stat.setString(1,accnum);
stat.setString(2,vcparticulars);
stat.setString(3,checknum);
stat.setDouble(4,mdeposit);
int rows=stat.executeUpdate();
try
{
dbcon.close();
}
catch(Exception e)
{
System.out.println(e);
}
if(rows==0)
{
System.out.println("Error insert");
}
else
{
out.println("Your transaction details have been recorded");
out.println("<br><br>");
out.println("<form method=post action=\"http://127.0.0.1:8000/servlet/fourthservlet\">");
out.println("<input type=submit value=report>");
out.println("</form>");
}
out.println("</body>");
out.println("</html>");
}
catch(Exception e)
{
System.out.println(e);
}
}
}
}
4) 第四个Servelt代码:(显示该Account Number报告详细细节)
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import java.util.Calendar;
import javax.sql.*;
import java.sql.*;
public class FourthServlet extends HttpServlet
{
// String accountnumber;
Connection dbcon;
public void doPost(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
dbcon=DriverManager.getConnection("jdbc:odbc:test","sa","");
}
catch(ClassNotFoundException e)
{
System.out.println("Database driver not found");
System.out.println(e.toString());
throw new UnavailableException(this,"Cannot connect to the database");
}
catch(Exception e)
{
System.out.println("UNKNOWN!?");
}
ServletContext context=getServletContext();
Object obj=context.getAttribute("accountNumber");
String accnum=obj.toString();
double amount=0.0;
PrintWriter out=res.getWriter();
res.setContentType("text/html");
try
{
PreparedStatement s=dbcon.prepareStatement("select mBalance from Account_Holder Where cAccount_id=?");
s.setString(1,accnum);
ResultSet result=s.executeQuery();
result.next();
if(result==null)
{
System.out.println("Error executing the query");
}
else
{
amount=result.getDouble(1);
}
}
catch(SQLException e)
{
System.out.println(e.toString());
}
out.println("<html>");
out.println("<body bgcolor=pink>");
out.println("<head>");
out.println("<title>");
out.println("Balance");
out.println("</title>");
out.println("</head>");
out.println("<b><u>Your balance details</u></b>");
out.println("<br>");
out.println("Account number: "+accnum);
out.println("<br>");
out.println("<b><font size=5 color=green> Balance statement</font></b>");
boolean rowfound=true;
out.println("<hr>");
out.println("<table cellpadding=20>");
out.println("<tr>");
out.println("<td>");
out.println("Account Number ");
out.println("</td>");
out.println("<td>");
out.println("Date ");
out.println("</td>");
out.println("<td>");
out.println("Amount Deposited(Rs) ");
out.println("</td>");
out.println("</tr>");
out.println("</table>");
out.println("<hr>");
int totalrows=0;
try
{
PreparedStatement s1=dbcon.prepareStatement("select count(*) from account_holder_transaction where cAccount_id=?");
s1.setString(1,accnum);
ResultSet r=s1.executeQuery();
r.next();
totalrows=r.getInt(1);
totalrows-=20;
}
catch(Exception e)
{
}
try
{
PreparedStatement s2=dbcon.prepareStatement("select cAccount_id,datepart(d,dDate_of_transaction),datepart(m,dDate_of_transaction),datepart(yy,dDate_of_transaction),mAmount from account_holder_transaction where cAccount_id=?");
s2.setString(1,accnum);
ResultSet result=s2.executeQuery();
rowfound=result.next();
int numrows=0;
int dd,mm,yy;
dd=mm=yy=0;
if(rowfound)
numrows=1;
String d=new String(" ");
while(rowfound)
{
if(numrows>totalrows)
{
dd=result.getInt(2);
mm=result.getInt(3);
yy=result.getInt(4);
double mdeposit=result.getDouble(5);
d=dd+"/"+mm+"/"+yy;
out.println("           ");
out.println(accnum);
out.println("           ");
out.println(d);
out.println("           ");
out.println(mdeposit);
out.println("<br>");
}
rowfound=result.next();
numrows++;
}
}
catch(Exception e)
{
System.out.println(e.toString());
}
out.println("</body>");
out.println("</html>");
out.close();
}//End doPost
}//End class definition
5)下面是创建数据库文件(CREATEEBDB.SQL)
/* Install EarnestBank database */
set nocount on
USE master
declare @dttm varchar(55)
select @dttm=convert(varchar,getdate(),113)
raiserror('Starting installation of EarnestBank Database at %s ....',1,1,@dttm) with nowait
--set dateformat mdy
GO
--sp_addlogin user1,null,EarnestBank
if exists (select * from sysdatabases where name='EarnestBank')
begin
raiserror('Dropping existing EarnestBank database ....',0,1)
DROP database EarnestBank
end
GO
CHECKPOINT
go
raiserror('Creating EarnestBank database....',0,1)
go
create DATABASE EarnestBank
GO
CHECKPOINT
GO
USE EarnestBank
GO
if db_name() <> 'EarnestBank'
raiserror('Error in installEarnestBank.SQL, "USE EarnestBank" failed! Killing the SPID now.'
,22,127) with log
GO
execute sp_dboption 'EarnestBank','trunc. log on chkpt.' ,'true'
checkpoint
6)创建数据库中对象CREATEEarnestBankOBJECTS.SQL文件
USE EarnestBank
go
/* -- Creating Objects for Earnest Bank*/
raiserror('Now at the create table section ....',0,1)
Go
raiserror('Creating EarnestBank_Registration....',0,1)
create table Registration
(
cRegistration_id int IDENTITY(100,1) not null primary key,
cFirst_name char(50) not null,
cLast_name char(50) not null,
cAddress char(50) not null,
cAccount_type char(30) not null,
mAnnual_income money null,
cPhone_no char(10) not null
)
go
raiserror('Creating EarnestBank_Account_Holder....',0,1)
create table Account_Holder
(
cAccount_id char(10) not null primary key,
cRegistration_id int not null references Registration(cRegistration_id),
mBalance money not null
)
go
raiserror('Creating EarnestBank_Transaction....',0,1)
create table Account_Holder_Transaction
(
cAccount_id char(10) not null references Account_Holder(cAccount_id),
dDate_of_transaction datetime not null,
vcParticulars varchar(50) not null,
cCheck_no char(10) null,
mAmount money not null
)
GO
raiserror('Creating EarnestBank_Counter....',0,1)
create table Counter
(
cCounter_id char(10) not null primary key,
cAddress char(50) not null,
mCashBalance money not null,
mMinBalance money not null
)
GO
raiserror('Creating EarnestBank_Counter_Transaction....',0,1)
create table Counter_Transaction
(
cTransaction_id char(10) not null primary key,
cCounter_id char(10) not null references Counter(cCounter_id),
cAccount_id char(10) not null references Account_Holder(cAccount_id),
dDate_of_transaction datetime not null,
mDebit_amount money null,
mCredit_amount money null
)
go
raiserror('Creating EarnestBank_Loan....',0,1)
create table Loan
(
cLoan_id char(10) not null primary key,
cLoan_type char(15) not null,
intRate int not null,
intLoan_period int not null,
intInstalment int not null
)
go
raiserror('Creating EarnestBank_Loan_Registration....',0,1)
create table Loan_Registration
(
cLoan_Registration_id char(10) not null primary key,
cFirst_name char(10) not null,
cLast_name char(10) not null,
cAddress char(60) not null,
cLoan_type char(10) not null,
cPhone char(10) not null,
mAnnual_income money not null,
mAmount_applied money not null,
)
go
raiserror('Creating EarnestBank_Loan_Details....',0,1)
create table Loan_Details
(
cLoan_id char(10) not null references Loan(cLoan_id),
cLoan_Registration_id char(10) not null references Loan_Registration(cLoan_Registration_id),
mLoan_amount money not null,
mLoan_amount_repaid money not null,
mBalance money not null,
dDate_of_sanction datetime not null,
intBal_no_installments int not null
)
go
raiserror('Creating EarnestBank_Login....',0,1)
create table Login
(
cAccount_id char(10) not null references Account_Holder(cAccount_id),
cPin_no char(10) not null
)
go
raiserror('Inserting EarnestBank_Registration....',0,1)
insert into Registration values('Diana','Helbert','Bay Road, Singapore 5892', 'Savings', 340000, '02163467')
insert into Registration values('Jim','Hopkins','Stockholm street, SW 678902', 'Current', 600000, '032234')
insert into Registration values('Diana','Hayden','10 Hays Street,NY 30570', 'Savings', 240000, '045678')
insert into Registration values('Bob','Meakins','23 SunLey House, CA 45678', 'Fixed Deposit', 400000, '02145')
insert into Registration values('Laurry','Helbert','Rock St.Seattle 234657', 'Fixed Deposit', 450000, '0416348')
insert into Registration values('Shane' , 'Cornway', '25,Mackin St. CA 31435', 'Savings', 200000, '041656')
go
raiserror('Inserting EarnestBank_Account_Holder....',0,1)
insert into Account_Holder values('AH0001',100,500000)
insert into Account_Holder values('AH0002',101,100000)
insert into Account_Holder values('AH0003',102,100000)
insert into Account_Holder values('AH0004',103,150000)
insert into Account_Holder values('AH0005',104,145000)
go
raiserror('Inserting EarnestBank_Account_Holder_Transaction....',0,1)
insert into Account_Holder_Transaction values('AH0001',07/24/01,'Cheque deposit',234123,2250)
insert into Account_Holder_Transaction values('AH0002',07/14/01,'Cheque deposit',234455,5000)
insert into Account_Holder_Transaction values('AH0003',07/04/01, 'Withdrawal',0,36000)
insert into Account_Holder_Transaction values('AH0004',07/24/01, 'Withdrawal',0,3000)
insert into Account_Holder_Transaction values('AH0005',07/09/01, 'Cheque deposit',289756,165000)
go
raiserror('Inserting EarnestBank_Counter....',0,1)
insert into Counter values('CT0001','Hummingway Street NY', 8000, 50000)
insert into Counter values('CT0002','Timothy Square NY', 9000, 50000)
insert into Counter values('CT0003','Sunley Estate CA', 15000, 70000)
insert into Counter values('CT0004','Bayer House LS', 50000, 50000)
insert into Counter values('CT0005','Mackinnon Street CA', 45000, 80000)
go
raiserror('Inserting EarnestBank_Counter_Transaction....',0,1)
insert into Counter_Transaction values('TD0001','CT0002','AH0002','05/2/01',0,11000)
insert into Counter_Transaction values('TD0002','CT0001','AH0005','07/24/01',0,20000)
insert into Counter_Transaction values('TD0003','CT0003','AH0001','07/12/01',25000,0)
insert into Counter_Transaction values('TD0004','CT0004','AH0004','08/24/01',0,50000)
insert into Counter_Transaction values('TD0005','CT0005','AH0003','02/24/01',70000,0)
go
raiserror('Inserting EarnestBank_Loan....',0,1)
insert into Loan values('L0001','PL',19,3,36)
insert into Loan values('L0002','CL',20,5,60)
insert into Loan values('L0003','HL',15,10,120)
insert into Loan values('L0004','SL',10,7,94)
insert into Loan values('L0005','BL',21,5,60)
go
raiserror('Inserting EarnestBank_Loan_Registration....',0,1)
insert into Loan_Registration values('LD001','Jonas','Smith','15, Mackinnon Street CA 31435','PL','91434556',500000,100000)
insert into Loan_Registration values('LD002','Jullianne','Andrews','27A, Bayer House LS 22534','HL','91535445',700000,400000)
insert into Loan_Registration values('LD003','Bob','Anderson','143/C, Hummingway Street NY 259CA','BL','97645676',1400000,400000)
insert into Loan_Registration values('LD004','Othello','Darwin','23, Sunley Estate CA 13246','CL','45634523',500000,200000)
insert into Loan_Registration values('LD005','Jesse','Barkins','45QS, Timothy Square NY 147CG','SL','23456734',100000,75000)
go
raiserror('Inserting EarnestBank_Loan_Details....',0,1)
insert into Loan_Details values('L0001','LD002',300000,50000,250000,'04/2/01',30)
insert into Loan_Details values('L0002','LD003',400000,400000,0,'05/15/01',0)
insert into Loan_Details values('L0003','LD005',1200000,400000,800000,'06/12/01',34)
insert into Loan_Details values('L0004','LD004',300000,275000,25000,'06/08/01',1)
insert into Loan_Details values('L0003','LD001',350000,300000,50000,'06/06/01',2)
go
raiserror('Inserting EarnestBank_Login....',0,1)
insert into Login values('AH0001','1001')
insert into Login values('AH0002','1005')
insert into Login values('AH0003','1251')
insert into Login values('AH0004','6129')
insert into Login values('AH0005','6613')
go
raiserror('Database is now ready for use...',0,1)
go
7)好了,接着该配置ODBC,命名为test,指向EarnestBank数据库
8)最后配置J2EE服务器,新建一个应用,再新建四个Web Component,把四个servlet分别放入,test.htm应该放在第一个Web Component中.注意应用的Context名为:
servlet;四个Alias名为:firstservlet,secondservlet,thirdservlet,fourthservlet
本文地址:http://com.8s8s.com/it/it15922.htm