📄 updateservlet.java
字号:
/* UpdateServlet.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 javax.naming.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import javax.sql.rowset.CachedRowSet;
import com.sun.rowset.CachedRowSetImpl;
public class UpdateServlet 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();
// 查找数据源并且获得连接
InitialContext ctx = new InitialContext();
DataSource ds=(DataSource)ctx.lookup("jdbc/DBConnCoreDS");
con = ds.getConnection();
// 为更新图书生成预备好的语句
PreparedStatement stmt = con.prepareStatement("update book " +
"set isbn = ?, " +
"title = ?, " +
"author = ?, " +
"pressname = ? " +
"where isbn = ?");
// 把修改过的图书属性设置为SQL输入参数
stmt.setString(1, req.getParameter("isbn"));
stmt.setString(2, req.getParameter("title"));
stmt.setString(3, req.getParameter("author"));
stmt.setString(4, req.getParameter("pressname"));
stmt.setString(5, req.getParameter("id"));
// 进行更新
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 + -