在不使用MVC分层的情况下用一个servlet完成转账业务
package com.bjpowernode.Bank.servlet;
import com.bjpowernode.Bank.exception.AppException;
import com.bjpowernode.Bank.exception.MoneyNotEnoughException;
import com.bjpowernode.oa.utils.DBUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
//@WebServlet("/bank/transfer")
public class AccountTransferServlet extends HttpServlet
{
//当前Servlet实际上负责了
//数据接收,核心业务处理,CRUD操作,界面的数据展示
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String fromActno = request.getParameter("fromActno");
String toActno = request.getParameter("toActno");
Double value = Double.parseDouble(request.getParameter("Value"));
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
PreparedStatement statement1 = null;
PreparedStatement statement2 = null;
try
{
connection = DBUtil.getConnection();
connection.setAutoCommit(false);
String sql = "select * from t_act where actno = ?";
statement = connection.prepareStatement(sql);
statement.setString(1,fromActno);
resultSet = statement.executeQuery();
if(resultSet.next())
{
System.out.println("我在这");
double balance = resultSet.getDouble("balance");
System.out.println(balance);
if(balance < value)
{
//余额不足
throw new MoneyNotEnoughException("余额不足");
}
else
{
String newSql = "update t_act set balance = balance - ? where actno = ?";
statement1 = connection.prepareStatement(newSql);
statement1.setDouble(1,value);
statement1.setString(2,fromActno);
int count = statement1.executeUpdate();
String sql2 = "update t_act set balance = balance + ? where actno = ?";
statement2 = connection.prepareStatement(sql2);
statement2.setDouble(1,value);
statement2.setString(2,toActno);
count = count + statement2.executeUpdate();
if(count != 2)
{
throw new AppException("App异常请联系管理员");
}
else
{
connection.commit();
out.println("转账成功");
}
}
}
}
catch (Exception e)
{
if (connection != null)
{
try
{
connection.rollback();
}
catch (SQLException ex)
{
throw new RuntimeException(ex);
}
}
//传的一定是构造方法我们传的值
out.println(e.getMessage());
}
finally
{
DBUtil.close(connection,statement,resultSet);
DBUtil.close(null,statement1,null);
DBUtil.close(null,statement2,null);
}
}
}
标签:Web,balance,JAVA,java,EE,connection,import,null,servlet
From: https://blog.51cto.com/u_16322355/8067835