📄 createservlet.java
字号:
/* CreateServlet.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 CreateServlet 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();
// 通过指定插入SQL的语句生成预备好的语句
PreparedStatement stmt = con.prepareStatement("insert into book(isbn,title,author,pressname) values(?,?,?,?)");
// 把新图书属性设置为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"));
// 执行SQL插入语句
stmt.executeUpdate();
stmt.close();
// 设置用于获取图书列表的SQL命令
rs.setCommand("select * from book");
// 运行SQL命令
rs.execute(con);
// 把行集作为一个请求属性进行存储
req.setAttribute("rs",rs);
// 把请求转发到相关URI,这些URI映射到ListServlet上以显示新的图书
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 + -