synchronizedbankservlet.java
来自「JAVA Servlet2.3外文书籍源码」· Java 代码 · 共 115 行
JAVA
115 行
package synchronization;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.Enumeration;
import java.util.Vector;
import java.util.Hashtable;
public class SynchronizedBankServlet extends HttpServlet
{
private Hashtable accounts;
private Vector userTransactions;
public void init() throws ServletException
{
resetValues();
}
public void doGet (HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
InOut.in();
String reset = req.getParameter("reset");
String fromAccount = req.getParameter("from");
String toAccount = req.getParameter("to");
String amount = req.getParameter("amount");
PrintWriter writer = res.getWriter();
writer.println("<html><head></head>");
writer.println("<body style=\"font-family:verdana;font-size:8pt\">");
// -- Reset the values --
if (reset!=null)
resetValues();
if ( (fromAccount!=null)
&& (toAccount!=null)
&& (amount!=null)
)
{
// -- A money transfer --
transfer(fromAccount, toAccount, amount);
showData(writer);
}
else
{
// -- Just list account values and transactions --
showData(writer);
}
writer.println("</body></html>");
writer.close();
InOut.out();
}
public void resetValues() throws ServletException
{
userTransactions=new Vector();
accounts=new Hashtable();
accounts.put("000001","1000");
accounts.put("000002","1000");
}
private void showData(PrintWriter writer)
{
// -- show account balances --
writer.println("<b>Account Balances</b><br><br>");
for (Enumeration keys=accounts.keys(); keys.hasMoreElements(); )
{
String thisKey=(String) keys.nextElement();
String thisBalance=(String) accounts.get(thisKey);
writer.println("Account "+thisKey+" has balance "+thisBalance+"<br>");
}
// -- show user transactions reversed --
writer.println("<br><b>User Transactions</b><br><br>");
int i=userTransactions.size()-1;
if (i>=0) writer.println("<b>"+userTransactions.elementAt(i)+"</b><br>");
while (--i>=0)
{
writer.println(""+userTransactions.elementAt(i)+"<br>");
}
}
private synchronized void transfer(String fromAccount, String toAccount, String amount)
{
int fromAccountBalance=new Integer((String)accounts.get(fromAccount)).intValue();
int newFromAccountBalance=fromAccountBalance-(new Integer(amount).intValue());
int toAccountBalance=new Integer((String)accounts.get(toAccount)).intValue();
int newToAccountBalance=toAccountBalance+(new Integer(amount).intValue());
try {Thread.sleep(5000);} catch (java.lang.InterruptedException ex) {}
accounts.put(fromAccount,""+newFromAccountBalance);
accounts.put(toAccount,""+newToAccountBalance);
String transaction="Transfer of "+amount+" from account "+fromAccount+" to account "+toAccount;
userTransactions.add(transaction);
}
}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?