身為軟體開發人員的你希望看到什麼樣子的程式碼呢,如果你看到以下的程式碼你會....
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page import="java.sql.*" %>
<%@ page import="java.util.*" %>
<!DOCTYPE html>
<html>
<head>
<title>User Management</title>
<style>
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
th, td {
padding: 8px;
text-align: left;
}
</style>
</head>
<body>
<%
// 設定資料庫連接參數
String jdbcUrl = "jdbc:mysql://localhost:3306/your_database_name"; // 修改為你的資料庫URL
String dbUser = "root"; // 修改為你的資料庫使用者名稱
String dbPassword = "password"; // 修改為你的資料庫密碼
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
// 儲存來自請求的參數
String action = request.getParameter("action");
String userId = request.getParameter("id");
String userName = request.getParameter("name");
String userEmail = request.getParameter("email");
try {
// 連接資料庫
Class.forName("com.mysql.cj.jdbc.Driver");
connection = DriverManager.getConnection(jdbcUrl, dbUser, dbPassword);
// 處理不同的操作
if ("add".equals(action) && userName != null && userEmail != null) {
// 新增用戶
String sql = "INSERT INTO users (name, email) VALUES (?, ?)";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, userName);
preparedStatement.setString(2, userEmail);
preparedStatement.executeUpdate();
out.println("<p style='color:green;'>User added successfully!</p>");
} else if ("delete".equals(action) && userId != null) {
// 刪除用戶
String sql = "DELETE FROM users WHERE id = ?";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1, Integer.parseInt(userId));
preparedStatement.executeUpdate();
out.println("<p style='color:green;'>User deleted successfully!</p>");
} else if ("update".equals(action) && userId != null && userName != null && userEmail != null) {
// 更新用戶資料
String sql = "UPDATE users SET name = ?, email = ? WHERE id = ?";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, userName);
preparedStatement.setString(2, userEmail);
preparedStatement.setInt(3, Integer.parseInt(userId));
preparedStatement.executeUpdate();
out.println("<p style='color:green;'>User updated successfully!</p>");
}
// 顯示所有用戶
String sql = "SELECT id, name, email FROM users";
preparedStatement = connection.prepareStatement(sql);
resultSet = preparedStatement.executeQuery();
%>
<h2>User Management</h2>
<!-- 顯示用戶列表 -->
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<%
while (resultSet.next()) {
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
String email = resultSet.getString("email");
%>
<tr>
<td><%= id %></td>
<td><%= name %></td>
<td><%= email %></td>
<td>
<form action="userDetails.jsp" method="post" style="display:inline;">
<input type="hidden" name="action" value="delete">
<input type="hidden" name="id" value="<%= id %>">
<button type="submit">Delete</button>
</form>
<form action="userDetails.jsp" method="post" style="display:inline;">
<input type="hidden" name="action" value="update">
<input type="hidden" name="id" value="<%= id %>">
<input type="text" name="name" value="<%= name %>" required>
<input type="email" name="email" value="<%= email %>" required>
<button type="submit">Update</button>
</form>
</td>
</tr>
<%
}
%>
</tbody>
</table>
<%
} catch (Exception e) {
// 錯誤處理
out.println("<p style='color:red;'>Error: " + e.getMessage() + "</p>");
} finally {
// 關閉連接和資源
if (resultSet != null) try { resultSet.close(); } catch (SQLException ignore) {}
if (preparedStatement != null) try { preparedStatement.close(); } catch (SQLException ignore) {}
if (connection != null) try { connection.close(); } catch (SQLException ignore) {}
}
%>
<!-- 新增用戶表單 -->
<h3>Add New User</h3>
<form action="userDetails.jsp" method="post">
<input type="hidden" name="action" value="add">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<button type="submit">Add User</button>
</form>
</body>
</html>
以上程式由chatGpt產生
看到上面的程式碼是不是有一種無所適從的感覺的,畫面的展示、商業邏輯與資料庫存取都寫在一起,難以維護,所以就出現了MVC企圖解決這個問題。MVC(Model View Control)在軟體工程是一種軟體架構模式,他告訴你一些原則,按照這樣的方式寫讓你可以比較好修改、好維護(高內聚低耦合、開放封閉原則)
controller
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
private UserService userService = new UserService();
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
String userId = req.getParameter("userId");
String password = req.getParameter("password");
boolean loginIsSuccess = userService.validateUser(userId, password);
if(loginIsSuccess){
User user = userService.getUserInfo(userId);
req.setAttribute("user", user);
req.getRequestDispatcher("WEB-INF/Success.jsp").forward(req,res);
}else {
req.getRequestDispatcher("WEB-INF/Fail.jsp").forward(req,res);
}
}
}
service
public class UserService {
private UserDao userDao = new UserDao();
public boolean validateUser(String userId, String password) {
UserDao dao = new UserDao();
User user = dao.findById(userId);
if(user == null){
return false;
}
if (user.getPassword().equals(password))
return true;
else
return false;
}
public User getUserInfo(String userId) {
User user = userDao.findById(userId);
long days = ChronoUnit.DAYS.between(user.getEntryDate(), LocalDate.now());
user.setJobDays(days);
return user;
}
}
dao
public class UserDao {
private static Map<String, User> dbMap;
static {
dbMap = new HashMap<String,User>();
User user1 = new User("1111","Bob","1234", LocalDate.of(2020,5,10));
User user2 = new User("2222","Alice","1234", LocalDate.of(2018,3,10));
User user3 = new User("3333","Joe","1234", LocalDate.of(2015,10,10));
dbMap.put("1111",user1);
dbMap.put("2222",user2);
dbMap.put("3333",user3);
}
public User findById(String userId) {
return dbMap.get(userId);
}
}
bean
public class User {
private String userName;
private String userId;
private String password;
private LocalDate entryDate ;
private long jobDays;
public User(String userId, String userName, String password, LocalDate entryDate) {
this.userName = userName;
this.userId = userId;
this.password = password;
this.entryDate = entryDate;
}
}
view
index.jsp
<h2>使用者登入:</h2>
<form action="LoginServlet" method="post">
<input type="text" id="userId" name="userId" placeholder="userId" required>
<input type="password" id="password" name="password" placeholder="Password" required>
<input type="submit" id="submit">
</form>
success.jsp
<html>
<head>
<title>歡迎光臨</title>
</head>
<body>
<h1>歡迎 <%= user.getUserName() %> ,您已經為公司賣命:<%= user.getJobDays() %>天了</h1>
</body>
</html>