Servlet学习笔记六Servlet之间的通信.docx
《Servlet学习笔记六Servlet之间的通信.docx》由会员分享,可在线阅读,更多相关《Servlet学习笔记六Servlet之间的通信.docx(27页珍藏版)》请在冰豆网上搜索。
![Servlet学习笔记六Servlet之间的通信.docx](https://file1.bdocx.com/fileroot1/2023-2/17/51d265d3-6b6a-41c0-a941-caf4d3e978b8/51d265d3-6b6a-41c0-a941-caf4d3e978b81.gif)
Servlet学习笔记六Servlet之间的通信
Servlet学习笔记(六)-----Servlet之间的通信
Servlet学习笔记(六)-----Servlet之间的通信
这是4个Servlet之间的通信
2.代码如下:
1)首先是test.htm文件,它作为客户端访问的页面
<!
DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.0Transitional//EN">
<HTML><HEAD>
<METAhttp-equiv=Content-Typecontent="text/html;charset=gb2312">
<METAcontent="MicrosoftFrontPage4.0"name=GENERATOR></HEAD>
<BODY>
<CENTER>
<H1>EarnestBank</H1></CENTER>
<FORMaction="http:
//127.0.0.1:
8000/servlet/firstservlet"method=post>enteryouraccountNumberhere<INPUTname=accnumsize="21">
<BR><BR><BR>enteryourpinNumberhere <INPUTname=pinnumsize="21"><BR>
<p>
<CENTER><INPUTtype=submitvalue=submit></CENTER></p>
</FORM></BODY></HTML>
2)第一个Servelt代码:
(作用是检验用户输入accountNumber和pinNumber是否合法)
importjavax.servlet.*;
importjavax.servlet.http.*;
importjava.io.*;
importjava.sql.*;
///importjavax.sql.*;
publicclassFirstServletextendsHttpServlet
{
staticConnectiondbcon;
staticStringresultToSecond="NA";
protectedvoiddoPost(HttpServletRequestreq,
HttpServletResponseresp)
throwsServletException,
java.io.IOException
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
dbcon=DriverManager.getConnection("jdbc:
odbc:
test","sa","");
System.out.println("Connectionestablished");
}
catch(Exceptione)
{
System.out.println("Databasenotfound!
");
}
//Createashareattribute创建一个共享属性
ServletContextcontext=this.getServletContext();
context.setAttribute("accountNumber","");
//得到从客户端发送过来的两个值
Stringaccnum=req.getParameter("accnum");
Stringpinnum=req.getParameter("pinnum");
//Checkwhethertheaccountnumandpinnumarevalid
try
{
PreparedStatementstat=dbcon.prepareStatement(
"select*fromLoginwherecAccount_id=?
andcPin_no=?
");
stat.setString(1,accnum);
stat.setString(2,pinnum);
ResultSetresult=stat.executeQuery();
if(result.next())
{
resultToSecond=result.getString
(1);
context.setAttribute("accountNumber",resultToSecond);
//theaccountivalidcallthesecondservlet通过验证后使用RequestDispatcher接口
//得到以URL为参数的Servlet的引用
RequestDispatcherdispatcher=context.getRequestDispatcher("/secondservlet");
if(dispatcher==null)
{
resp.sendError(resp.SC_NO_CONTENT);
}
//把请求提交或者委派给第二个Servlet
dispatcher.forward(req,resp);
try
{
dbcon.close();
}
catch(Exceptione)
{
System.out.println(e.toString());
}
}
else
{
resp.setContentType("text/html");
PrintWriterout=resp.getWriter();
out.println("<html><bodybgcolor=pink>");
out.println("Theaccountisinvalid");
out.println("<br><br>");
out.println("</body></html>");
resultToSecond="NA";
out.close();
}
}
catch(Exceptione){System.out.println(e);}
}
}
3)第二个Servelt代码:
(作用是显示AccountNumber,并允许用户输入Chequenumber和支票金额amount)
importjavax.servlet.*;
importjavax.servlet.http.*;
importjava.io.*;
importjava.sql.*;
///importjavax.sql.*;
//通过用getAttribute()函数得到帐号,显示用户账单号。
点击deposit按钮,调用第三个Servlet
publicclassSecondServletextendsHttpServlet
{
Connectiondbcon;
publicvoidservice(ServletRequestreq,ServletResponseresp)
throwsServletException,java.io.IOException
{
resp.setContentType("text/html");
PrintWriterout=resp.getWriter();
//Accessingtheaccountnumberfromtheservletcontext
ServletContextcontext=this.getServletContext();
Stringvalue=(String)context.getAttribute("accountNumber");
out.println("<html><head>");
out.println("<METAhttp-equiv=Content-Typecontent=\"text/html;charset=gb2312\">");
out.println("<METAcontent=\"MSHTML6.00.2600.0\"name=GENERATOR></HEAD>");
out.println("<body><CENTER><H1>EarnestBank</H1></CENTER>");
out.println("<formaction=http:
//127.0.0.1:
8000/servlet/thirdservletmethod=post>");
out.println("<b>Clickthedepositbuttontodeposityourmoney</b>");
out.println("<table>");
out.println("<tr><td>Accountnumber:
</td><td>"+value+"</td></tr>");
out.println("<tr><td>Chequenumber:
</td><td><inputtype=textname=checknum></td></tr>");
out.println("<tr><td>Entertheamounttobedeposited:
</td><td><inputtype=textname=amountvalue=0></td></tr>");
out.println("</table>");
out.println("<inputtype=submitvalue=deposit>");
out.println("<BR></form>");
out.println("</body></html>");
}
}
4)第三个Servelt代码:
(作用是显示数据插入成功,并允于用户查看交易报告)
importjavax.servlet.*;
importjavax.servlet.http.*;
importjava.io.*;
importjava.sql.*;
///importjavax.sql.*;
publicclassThirdServletextendsHttpServlet
{
Connectiondbcon;
StringaccountNumber;
protectedvoiddoPost(HttpServletRequestreq,
HttpServletResponseresp)
throwsServletException,
java.io.IOException
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
dbcon=DriverManager.getConnection("jdbc:
odbc:
test","sa","");
System.out.println("Connectionestablished");
}
catch(Exceptione)
{
System.out.println("Databasenotfound!
");
}
//Accessingtheaccountnumberfromtheservletcontext
ServletContextcontext=this.getServletContext();
Stringaccnum=(String)context.getAttribute("accountNumber");
resp.setContentType("text/html");
PrintWriterout=resp.getWriter();
Stringamount=req.getParameter("amount");
Stringchecknum=req.getParameter("checknum");
out.println("<html><bodybgcolor=pink>");
booleancheckcorrect=true;
booleanamountcorrect=true;
if(checknum.length()==0)
{
checkcorrect=false;
out.println("Plsenterthechequenumberproperly");
}
doublemdeposit=Double.parseDouble(amount);
if(mdeposit<=0)
{
amountcorrect=false;
out.println("Thedepositamountmustbevalid");
out.println("<br>Plsreentertheamount");
}
if(checkcorrect&&amountcorrect)
{
try
{
PreparedStatementstat=dbcon.prepareStatement(
"insertAccount_Holder_Transactionvalues(?
getDate(),?
?
?
)");
Stringvcparticulars=newString("ChequeDeposit");
stat.setString(1,accnum);
stat.setString(2,vcparticulars);
stat.setString(3,checknum);
stat.setDouble(4,mdeposit);
introws=stat.executeUpdate();
try
{
dbcon.close();
}
catch(Exceptione)
{
System.out.println(e);
}
if(rows==0)
{
System.out.println("Errorinsert");
}
else
{
out.println("Yourtransactiondetailshavebeenrecorded");
out.println("<br><br>");
out.println("<formmethod=postaction=\"http:
//127.0.0.1:
8000/servlet/fourthservlet\">");
out.println("<inputtype=submitvalue=report>");
out.println("</form>");
}
out.println("</body>");
out.println("</html>");
}
catch(Exceptione)
{
System.out.println(e);
}
}
}
}
4)第四个Servelt代码:
(显示该AccountNumber报告详细细节)
importjavax.servlet.*;
importjavax.servlet.http.*;
importjava.io.*;
importjava.util.*;
importjava.util.Calendar;
importjavax.sql.*;
importjava.sql.*;
publicclassFourthServletextendsHttpServlet
{
//Stringaccountnumber;
Connectiondbcon;
publicvoiddoPost(HttpServletRequestreq,HttpServletResponseres)throwsServletException,IOException
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
dbcon=DriverManager.getConnection("jdbc:
odbc:
test","sa","");
}
catch(ClassNotFoundExceptione)
{
System.out.println("Databasedrivernotfound");
System.out.println(e.toString());
thrownewUnavailableException(this,"Cannotconnecttothedatabase");
}
catch(Exceptione)
{
System.out.println("UNKNOWN!
?
");
}
ServletContextcontext=getServletContext();
Objectobj=context.getAttribute("accountNumber");
Stringaccnum=obj.toString();
doubleamount=0.0;
PrintWriterout=res.getWriter();
res.setContentType("text/html");
try
{
PreparedStatements=dbcon.prepareStatement("selectmBalancefromAccount_HolderWherecAccount_id=?
");
s.setString(1,accnum);
ResultSetresult=s.executeQuery();
result.next();
if(result==null)
{
System.out.println("Errorexecutingthequery");
}
else
{
amount=result.getDouble
(1);
}
}
catch(SQLExceptione)
{
System.out.println(e.toString());
}
out.println("<html>");
out.println("<bodybgcolor=pink>");
out.println("<head>");
out.println("<title>");
out.println("Balance");
out.println("</title>");
out.println("</head>");
out.println("<b><u>Yourbalancedetails</u></b>");
out.println("<br>");
out.println("Accountnumber:
"+accnum);
out.println("<br>");
out.println("<b><fontsize=5color=green>Balancestatement</font></b>");
booleanrowfound=true;
out.println("<hr>");
out.println("<tablecellpadding=20>");
out.println("<tr>");
out.println("<td>");
out.println("AccountNumber");
out.println("</td>");
out.println("<td>");
out.println("Date");
out.println("</td>");
out.println("<td>");
out.println("AmountDeposited(Rs)");
out.println("</td>");
out.println("</tr>");
out.println("</table>");
out.println("<hr>");
&nbs
p;
inttotalrows=0;
try
{
PreparedStatements1=dbcon.prepareStatement("selectcount(*)fromaccount_holder_transactionwherecAccount_id=?
");
s1.setString(1,accnum);
ResultSetr=s1.executeQuery();
r.next();
totalrows=r.getInt
(1);
totalrows-=20;
}
catch(Exceptione)
{
}
try
{