<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<center>
<h4>输入页面</h4>
<form action="update" method="get">
名称:<input name="bname" /><br/>
介绍:<input name="bdesc" /><br/>
<input type="submit" value="增加"/>
</form>
</center>
</body>
</html>
Update.java:
package bean;
public class Update {
private Integer id;
private String bname;
private String bdesc;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getBname() {
return bname;
}
public void setBname(String bname) {
this.bname = bname;
}
public String getBdesc() {
return bdesc;
}
public void setBdesc(String bdesc) {
this.bdesc = bdesc;
}
}
UpdateDao.java:
package dao;
import org.apache.commons.dbutils.QueryRunner;
import org.junit.Test;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class UpdateDao {
public boolean updateByC3p0(String bname, String bdesc) {
//数据源
ComboPooledDataSource ds = new ComboPooledDataSource();
//获取连接
QueryRunner qr = new QueryRunner(ds);
String sql = "insert into books values(null,?,?)";
//update:增删改 query:查询
boolean t=true;
try {
int count = qr.update(sql, bname,bdesc);
if(count>0) {
t=true;
}else {
t=false;
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return t;
}
}
UpdateService.java:
package service;
import dao.UpdateDao;
public class UpdateService {
public boolean update(String bname,String bdesc) {
return new UpdateDao().updateByC3p0(bname, bdesc);
}
}
UpdateServlet.java:
package web.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import service.UpdateService;
public class UpdateServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//System.out.println("get请求过来了....");
//获取请求过来的参数
String bname = request.getParameter("bname");
String bdesc = request.getParameter("bdesc");
ServletResponse resp;
//业务层 LoginService 调用
//响应乱码解码
response.setContentType("text/html;charset=utf-8");
boolean b = new UpdateService().update(bname, bdesc);
PrintWriter writer = response.getWriter();
if(b==false) {
//登录失败
writer.println("<font color='red'>添加失败</font>");
}else {
//登录成功
writer.println("添加成功");
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
输入界面:
添加成功: