dao层代码如下:
package beyond. transfer. dao; import java. sql. Connection;
import java. sql. SQLException; import org. apache. commons. dbutils. QueryRunner; import beyond. utils. DataSourceUtils;
import beyond. utils. MyDataSourceUtils; public class TransferDao { public void out ( String out, double money) throws SQLException { QueryRunner runner = new QueryRunner ( ) ; Connection conn = MyDataSourceUtils. getCurrentConnection ( ) ; String sql = "update account set money= money-? where name=?" ; runner. update ( conn, sql, money, out) ; } public void in ( String in, double money) throws SQLException { QueryRunner runner = new QueryRunner ( ) ; Connection conn = MyDataSourceUtils. getCurrentConnection ( ) ; String sql = "update account set money= money+? where name=?" ; runner. update ( conn, sql, money, in) ; } }
service层代码如下:
package beyond. transfer. service; import java. sql. Connection;
import java. sql. SQLException; import beyond. transfer. dao. TransferDao;
import beyond. utils. DataSourceUtils;
import beyond. utils. MyDataSourceUtils; public class TransferService { public boolean transfer ( String out, String in, double money) { TransferDao dao = new TransferDao ( ) ; boolean isTransferSuccess = true ; Connection conn = null; try { MyDataSourceUtils. startTransaction ( ) ; dao. out ( out, money) ; dao. in ( in, money) ; } catch ( SQLException e) { isTransferSuccess = false ; try { MyDataSourceUtils. rollback ( ) ; } catch ( SQLException e1) { e1. printStackTrace ( ) ; } e. printStackTrace ( ) ; } finally { try { MyDataSourceUtils. commit ( ) ; } catch ( SQLException e) { e. printStackTrace ( ) ; } } return isTransferSuccess; } }
web层代码如下:
package beyond. transfer. web; import java. io. IOException;
import javax. servlet. ServletException;
import javax. servlet. http. HttpServlet;
import javax. servlet. http. HttpServletRequest;
import javax. servlet. http. HttpServletResponse; import beyond. transfer. service. TransferService; public class TransferServlet extends HttpServlet { public void doGet ( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String out = request. getParameter ( "out" ) ; String in = request. getParameter ( "in" ) ; String moneyStr = request. getParameter ( "money" ) ; double money= Double. parseDouble ( moneyStr) ; TransferService service = new TransferService ( ) ; boolean isTransferSuccess = service. transfer ( out, in, money) ; response. setContentType ( "text/html;charset=UTF-8" ) ; if ( isTransferSuccess) { response. getWriter ( ) . write ( "转账成功!!!" ) ; } else { response. getWriter ( ) . write ( "转账失败!!!" ) ; } } public void doPost ( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet ( request, response) ; }
}