MVC架构代码简单演示

代码演示如下

1
2
3
4
5
6
7
8
9
10
11
12
package com.xiaoguan.bank.exceptions;

public class AppException extends Exception{
public AppException() {
super();
}

public AppException(String message) {
super(message);
}
}

1
2
3
4
5
6
7
8
9
10
11
12
package com.xiaoguan.bank.exceptions;

public class MoneyNotEnough extends Exception{
public MoneyNotEnough() {
super();
}

public MoneyNotEnough(String message) {
super(message);
}
}

1
2
3
4
5
6
7
8
9
10
11
12
package com.xiaoguan.bank.exceptions;

public class MoneyNotEnough extends Exception{
public MoneyNotEnough() {
super();
}

public MoneyNotEnough(String message) {
super(message);
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
package com.xiaoguan.bank.mvc;

import com.xiaoguan.bank.utils.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class AccountDao {//负责数据处理,Data Access Object数据访问对象,一般情况一张表对应一个DAO

public AccountDao() {
}

public int insert(Account act){
Connection conn=null;
PreparedStatement ps=null;
int count=0;
try {
conn = DBUtil.getConnection();
String sql="insert into t_act(actno,balance) values(?,?)";
ps=conn.prepareStatement(sql);
ps.setString(1,act.getActno());
ps.setDouble(2,act.getBalance());
count=ps.executeUpdate();
} catch (SQLException e) {
throw new RuntimeException(e);
}finally {
DBUtil.close(null,ps,null);
}
return count;
}
public int deleteById(Long id){
Connection conn=null;
PreparedStatement ps=null;
int count=0;
try {
conn = DBUtil.getConnection();
String sql="delete from t_act where id=?";
ps=conn.prepareStatement(sql);
ps.setLong(1,id);
count=ps.executeUpdate();
} catch (SQLException e) {
throw new RuntimeException(e);
}finally {
DBUtil.close(null,ps,null);
}
return count;
}
public int update(Account account){
Connection conn=null;
PreparedStatement ps=null;
int count=0;
try {
conn = DBUtil.getConnection();
String sql="update t_act set balance=?,actno=? where id=?";
ps=conn.prepareStatement(sql);
ps.setDouble(1,account.getBalance());
ps.setString(2,account.getActno());
ps.setLong(3,account.getId());
count=ps.executeUpdate();
} catch (SQLException e) {
throw new RuntimeException(e);
}finally {
DBUtil.close(null,ps,null);
}
return count;
}
public Account selectByActno(String actno){
Connection conn=null;
PreparedStatement ps=null;
ResultSet rs=null;
Account account=new Account();
try {
conn = DBUtil.getConnection();
String sql="select id,balance from t_act where actno=?";
ps=conn.prepareStatement(sql);
ps.setString(1,actno);
rs=ps.executeQuery();
if(rs.next()){
Long id= rs.getLong("id");
Double balance=rs.getDouble("balance");
account.setActno(actno);
account.setId(id);
account.setBalance(balance);
}

} catch (SQLException e) {
throw new RuntimeException(e);
}finally {
DBUtil.close(null,ps,rs);
}
return account;
}
public List<Account> selectAll(){
Connection conn=null;
PreparedStatement ps=null;
ResultSet rs=null;
List<Account> accounts=new ArrayList<>();
try {
conn = DBUtil.getConnection();
String sql="select id,balance,actno from t_act ";
ps=conn.prepareStatement(sql);
rs=ps.executeQuery();
while(rs.next()){
Long id= rs.getLong("id");
Double balance=rs.getDouble("balance");
String actno=rs.getString("actno");
accounts.add(new Account(id,actno,balance));
}

} catch (SQLException e) {
throw new RuntimeException(e);
}finally {
DBUtil.close(null,ps,rs);
}
return accounts;
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package com.xiaoguan.bank.mvc;

import com.xiaoguan.bank.exceptions.AppException;
import com.xiaoguan.bank.exceptions.MoneyNotEnough;
import com.xiaoguan.bank.utils.DBUtil;

import java.sql.Connection;
import java.sql.SQLException;

public class AccountService {
Connection conn=null;
private AccountDao accountDao=new AccountDao();
public void transfer(String fromActno,String toActno,double money) throws MoneyNotEnough, AppException { //完成转账逻辑
try{
conn=DBUtil.getConnection();
conn.setAutoCommit(false);
Account fromAccount = accountDao.selectByActno(fromActno);
if(fromAccount.getBalance()<money){
throw new MoneyNotEnough("对不起,余额不足");
}
Account toAccount=accountDao.selectByActno(toActno);
fromAccount.setBalance(fromAccount.getBalance()-money);
toAccount.setBalance(toAccount.getBalance()+money);
int count=accountDao.update(fromAccount);
count+=accountDao.update(toAccount);
if (count!=2) {
throw new AppException("转账出错了");
}
conn.commit();
}catch(SQLException e){
if (conn!=null){
try {
conn.rollback();
} catch (SQLException ex) {
e.printStackTrace();
}
}
throw new AppException("转账出错了");
}catch (Exception e){
if (conn!=null){
try {
conn.rollback();
} catch (SQLException ex) {
e.printStackTrace();
}
}
throw new AppException("转账出错了");
}finally {
DBUtil.close(conn,null,null);
}
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package com.xiaoguan.bank.mvc;

import com.xiaoguan.bank.exceptions.AppException;
import com.xiaoguan.bank.exceptions.MoneyNotEnough;
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;
@WebServlet("/transfer")
public class AccountServlet extends HttpServlet {//作为Controller
AccountService accountService=new AccountService();
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String fromActno = request.getParameter("fromActno");
String toActno = request.getParameter("toActno");
double money = Double.parseDouble(request.getParameter("money"));

try {
accountService.transfer(fromActno,toActno,money);
response.sendRedirect(request.getContextPath()+"/success.jsp");
} catch (MoneyNotEnough e) {
response.sendRedirect(request.getContextPath()+"/moneyNotEnough.jsp");
} catch (Exception e) {
response.sendRedirect(request.getContextPath()+"/error.jsp");
}
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package com.xiaoguan.bank.utils;

import java.sql.*;
import java.util.ResourceBundle;

public class DBUtil {
private DBUtil() {}
private static ResourceBundle bundle=ResourceBundle.getBundle("resources/JDBC");
private static String driver=bundle.getString("driver");
private static String url=bundle.getString("url");
private static String username=bundle.getString("username");
private static String password=bundle.getString("password");
static {
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}

private static ThreadLocal<Connection> local=new ThreadLocal<>();
public static Connection getConnection() throws SQLException {
Connection conn = local.get();
if (conn == null) {
conn=DriverManager.getConnection(url,username,password);
local.set(conn);
}
return conn;
}

public static void close(Connection conn, PreparedStatement ps, ResultSet rs){
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
if (ps != null) {
try {
ps.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
if (conn != null) {
try {
conn.close();
local.remove();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
}

该程序还右许多缺陷,比如并没有考虑并发的情况,自己转自己和多人访问会有错误,还有没有写出各部分相对应的接口来,这些都做了才相对规范。

1
2
3
4
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/mvc
username=root
password=密码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<%--
Created by IntelliJ IDEA.
User: xiaoguan
Date: 2023/5/24
Time: 20:28
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>转账失败</title>
</head>
<body>
<h1>转账失败</h1>
</body>
</html>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<%--
Created by IntelliJ IDEA.
User: xiaoguan
Date: 2023/5/24
Time: 14:22
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<base href="${pageContext.request.scheme}://${pageContext.request.serverName}:${pageContext.request.serverPort}/${pageContext.request.contextPath}/">
<title>银行账户转账</title>
</head>
<body>
<form action="transfer" method="post">
转出账号:<input type="text" name="fromActno" /><br>
转入账号:<input type="text" name="toActno"/><br>
转账金额:<input type="text" name="money"><br>
<input type="submit" value="转账">
</form>
</body>
</html>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<%--
Created by IntelliJ IDEA.
User: xiaoguan
Date: 2023/5/24
Time: 20:31
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>余额不足</title>
</head>
<body>
<h1>余额不足,转账失败</h1>
</body>
</html>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<%--
Created by IntelliJ IDEA.
User: xiaoguan
Date: 2023/5/24
Time: 20:28
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>转账成功</title>
</head>
<body>
<h1>转账成功</h1>
</body>
</html>