📄 deleteservlet.java
字号:
/* DeleteServlet.java */
package mvcBook;
import javax.servlet.ServletException;
import javax.servlet.ServletConfig;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import javax.naming.*;
import javax.sql.rowset.CachedRowSet;
import com.sun.rowset.CachedRowSetImpl;
public class DeleteServlet extends HttpServlet {
public void init(ServletConfig config) throws ServletException {
super.init(config);
}
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException {
doGet(req, res);
}
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException {
Connection con = null;
try {
req.setCharacterEncoding("GBK");
// 生成一个新的缓冲存储集
CachedRowSet rs = new CachedRowSetImpl();
// 生成JNDI初始上下文环境
InitialContext ctx = new InitialContext();
// 查找JDBC数据源的JNDI名字
DataSource ds = (DataSource)ctx.lookup("jdbc/DBConnCoreDS");
// 获得JDBC连接
con = ds.getConnection();
// 生成预备好的语句以便发出用于删除的SQL语句
PreparedStatement stmt = con.prepareStatement("delete from book where isbn = ?");
// 设置选定的图书号作为一个SQL输入参数
stmt.setString(1, req.getParameter("id"));
// 执行SQL
stmt.executeUpdate();
stmt.close();
// 设置用于获取图书列表的SQL命令
rs.setCommand("select * from book");
// 运行SQL命令
rs.execute(con);
// 把行集作为一个请求属性进行存储
req.setAttribute("rs",rs);
// 把请求转发到相关URI,这些URI映射到List.jsp页面上以显示新的图书
getServletContext().getRequestDispatcher("/List.jsp").forward(req, res);
}
catch(Exception ex) {
throw new ServletException(ex);
}
finally {
try {
if(con != null) con.close();
}
catch(Exception ex) {
throw new ServletException(ex);
}
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -