写一段servlet+JDBC完成MVC架构下的增删改查的代码
时间: 2024-10-08 12:03:58 浏览: 54
jdbc+servlet+javabean+mysql的数据库增删改查的案例
5星 · 资源好评率100%
在MVC(Model-Controller)架构下,Servlet通常作为控制器,负责处理HTTP请求,而JDBC用于数据库操作。下面是一个简单的示例,展示如何使用Servlet和JDBC实现CRUD操作:
```java
// 导入必要的包
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class UserController extends HttpServlet {
private static final String DATABASE_URL = "jdbc:mysql://localhost:3306/mydb";
private static final String USER_TABLE = "users";
private static final String USER_ID_COLUMN = "id";
private static final String USER_NAME_COLUMN = "name";
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 获取数据
int id = Integer.parseInt(request.getParameter("id"));
String action = request.getParameter("action");
String userName = request.getParameter("username");
String sql;
try (Connection conn = DriverManager.getConnection(DATABASE_URL, "root", "password");) {
if ("add".equals(action)) {
sql = "INSERT INTO " + USER_TABLE + "(name) VALUES (?)";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, userName);
pstmt.executeUpdate();
response.sendRedirect("view-users.jsp");
} else if ("update".equals(action)) {
sql = "UPDATE " + USER_TABLE + " SET name=? WHERE " + USER_ID_COLUMN + "=?";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, userName);
pstmt.setInt(2, id);
pstmt.executeUpdate();
response.sendRedirect("view-users.jsp");
} else if ("delete".equals(action)) {
sql = "DELETE FROM " + USER_TABLE + " WHERE " + USER_ID_COLUMN + "=?";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, id);
pstmt.executeUpdate();
response.sendRedirect("view-users.jsp");
} else {
throw new IllegalArgumentException("Invalid action: " + action);
}
} catch (SQLException e) {
response.getWriter().println("Error: " + e.getMessage());
}
}
// 其他方法如get请求、异常处理等可根据需要添加
}
```
在这个例子中,`doPost`方法处理POST请求,并根据传来的`action`参数执行对应的增删改操作。注意,这是一个简化的示例,实际生产环境中需要更全面的错误处理以及安全性措施。
阅读全文