代码实现了简单的增删改查功能,应付考试做得并不完整;因为只实现功能,并没有做页面美化,所以有点丑,表介意
目录结构
页面展示
index.jsp
insertPage.jsp
updatePage.jsp
关键代码示例
增加模块
点击增加按钮,跳转增加页面;输入信息后点击提交按钮,页面向servlet发送post请求,servlet接收name值,调用InsertBean传入参数,InsertBean调用util的插入方法执行sql语句;后面板块流程类似。
insertPage.jsp
$("button[type='button']").click(function (){
$.ajax({
type: "post",
url: "insert",
data: {
name: $("input[name='name']").val()
},
success: function (data) {
if (data === "success"){
alert("新增成功");
window.name = "true";
location.href = "index.jsp";
}else if (data === "error"){
alert("新增数据失败");
}else if (data === "sql"){
alert("sql执行错误");
}else{
alert("请输入内容!");
}
},
error: function (error){
alert(error)
}
});
});
InsertServlet.java
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
String name = req.getParameter("name");
PrintWriter out = resp.getWriter();
if (name != null && name.length() > 0){
InsertBean insertBean = new InsertBean();
int res = insertBean.addUser(name);
if (res > 0){
req.setAttribute("info", "添加成功");
out.print("success");
}else if (res == 0){
req.setAttribute("error", "插入数据失败");
out.print("error");
}else{
req.setAttribute("error", "sql执行错误");
out.print("sql");
}
}else{
out.print("length");
}
out.close();
}
insertBean.java
public int addUser(String name){
DbPreparedUtil util = new DbPreparedUtil();
String sql = "insert into msg (name) value (?)";
try {
int res = util.executeUpdate(sql, name);
return res;
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
util.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return -1;
}
完整内容在链接中——>源代码及sql文件链接