jsp+servlet实现最简单的增删改查代码分享
话不多说,请看代码
packageceet.ac.cn.dao;
importjava.sql.Connection;
importjava.sql.PreparedStatement;
importjava.sql.ResultSet;
importjava.sql.SQLException;
importjava.util.ArrayList;
importjava.util.List;
importceet.ac.cn.model.Admin;
publicclassAdminDao{
publicList<Admin>getAllAdmin(){//查询所有信息
List<Admin>list=newArrayList<Admin>();//创建集合
Connectionconn=DbHelper.getConnection();
Stringsql="select*fromadmin";//SQL查询语句
try{
PreparedStatementpst=conn.prepareStatement(sql);
ResultSetrst=pst.executeQuery();
while(rst.next()){
Adminadmin=newAdmin();
admin.setId(rst.getInt("id"));//得到ID
admin.setUsername(rst.getString("username"));
admin.setUserpwd(rst.getString("userpwd"));
list.add(admin);
}
rst.close();//关闭
pst.close();//关闭
}catch(SQLExceptione){
e.printStackTrace();//抛出异常
}
returnlist;//返回一个集合
}
publicbooleanaddAdmin(Adminadmin){//添加信息
Stringsql="INSERTINTO`admin`(`id`,`username`,`userpwd`)VALUES(?,?,?)";//添加的SQL语句
Connectionconn=DbHelper.getConnection();
try{
PreparedStatementpst=conn.prepareStatement(sql);
pst.setInt(1,admin.getId());
pst.setString(2,admin.getUsername());
pst.setString(3,admin.getUserpwd());
intcount=pst.executeUpdate();
pst.close();
returncount>0?true:false;//是否添加的判断
}catch(SQLExceptione){
e.printStackTrace();
}
returnfalse;
}
publicbooleanupdateAdmin(Adminadmin){//修改
Stringsql="UPDATE`admin`SET`username`=?,`userpwd`=?WHERE`id`=?";//修改的SQL语句,根据ID修改
Connectionconn=DbHelper.getConnection();
try{
PreparedStatementpst=conn.prepareStatement(sql);
pst.setString(1,admin.getUsername());
pst.setString(2,admin.getUserpwd());
pst.setInt(3,admin.getId());//根据的ID
intcount=pst.executeUpdate();
pst.close();//关闭
returncount>0?true:false;//是否修改的判断
}catch(SQLExceptione){
e.printStackTrace();
}
returnfalse;
}
publicbooleandeleteAdmin(intid){//删除
Stringsql="deletefromadminwhereid=?";//删除的SQL语句,根据ID删除
Connectionconn=DbHelper.getConnection();
try{
PreparedStatementpst=conn.prepareStatement(sql);
pst.setInt(1,id);
intcount=pst.executeUpdate();
pst.close();
returncount>0?true:false;//是否删除的判断
}catch(SQLExceptione){
e.printStackTrace();
}
returnfalse;
}
publicAdminselectAdminById(intid){//根据ID进行查询
Connectionconn=DbHelper.getConnection();
Stringsql="select*fromadminwhereid="+id;
Adminadmin=null;
try{
PreparedStatementpst=conn.prepareStatement(sql);
ResultSetrst=pst.executeQuery();
while(rst.next()){
admin=newAdmin();
admin.setId(rst.getInt("id"));
admin.setUsername(rst.getString("username"));
admin.setUserpwd(rst.getString("userpwd"));
}
rst.close();
pst.close();
}catch(SQLExceptione){
e.printStackTrace();
}
returnadmin;//返回
}
}
packageceet.ac.cn.dao;
importjava.sql.Connection;
importjava.sql.DriverManager;
/**
*连接数据库
*@author画船听雨眠
*
*/
publicclassDbHelper{
privatestaticStringurl="jdbc:mysql://localhost:3306/admin";//数据库地址
privatestaticStringuserName="root";//数据库用户名
privatestaticStringpassWord="359129127";//数据库密码
privatestaticConnectionconn=null;
privateDbHelper(){
}
publicstaticConnectiongetConnection(){
if(null==conn){
try{
Class.forName("com.mysql.jdbc.Driver");
conn=DriverManager.getConnection(url,userName,passWord);
}catch(Exceptione){
e.printStackTrace();
}
}
returnconn;
}
publicstaticvoidmain(String[]args){//测试数据库是否连通
System.err.println(getConnection());
}
}
packageceet.ac.cn.model;
importjava.io.Serializable;
publicclassAdminimplementsSerializable{//数据封装类
privatestaticfinallongserialVersionUID=1L;
privateintid;
privateStringusername;
privateStringuserpwd;
publicintgetId(){
returnid;
}
publicvoidsetId(intid){
this.id=id;
}
publicStringgetUsername(){
returnusername;
}
publicvoidsetUsername(Stringusername){
this.username=username;
}
publicStringgetUserpwd(){
returnuserpwd;
}
publicvoidsetUserpwd(Stringuserpwd){
this.userpwd=userpwd;
}
}
packageceet.ac.cn.servlet;
importjava.io.IOException;
importjavax.servlet.ServletException;
importjavax.servlet.http.HttpServlet;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
importceet.ac.cn.dao.AdminDao;
importceet.ac.cn.model.Admin;
publicclassAddServletextendsHttpServlet{//添加数据
privatestaticfinallongserialVersionUID=1L;
protectedvoiddoGet(HttpServletRequestreq,HttpServletResponseresp)
throwsServletException,IOException{
this.doPost(req,resp);
}
protectedvoiddoPost(HttpServletRequestreq,HttpServletResponseresp)
throwsServletException,IOException{
Stringusername=req.getParameter("username");
Stringuserpwd=req.getParameter("userpwd");
Adminadmin=newAdmin();
admin.setUsername(newString(username.getBytes("ISO-8859-1"),"UTF-8"));//转值,中文需要转换为utf-8
admin.setUserpwd(newString(userpwd.getBytes("ISO-8859-1"),"UTF-8"));
AdminDaodao=newAdminDao();
dao.addAdmin(admin);
req.getRequestDispatcher("ShowServlet").forward(req,resp);
}
}
packageceet.ac.cn.servlet;
importjava.io.IOException;
importjavax.servlet.ServletException;
importjavax.servlet.http.HttpServlet;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
importceet.ac.cn.dao.AdminDao;
publicclassDeleteServletextendsHttpServlet{//删除数据
privatestaticfinallongserialVersionUID=1L;
protectedvoiddoGet(HttpServletRequestreq,HttpServletResponseresp)
throwsServletException,IOException{
this.doPost(req,resp);
}
protectedvoiddoPost(HttpServletRequestreq,HttpServletResponseresp)
throwsServletException,IOException{
StringidStr=req.getParameter("id");//删除数据的ID,根据ID删除
if(idStr!=null&&!idStr.equals("")){
intid=Integer.valueOf(idStr);
AdminDaodao=newAdminDao();
dao.deleteAdmin(id);
}
req.getRequestDispatcher("ShowServlet").forward(req,resp);
}
}
packageceet.ac.cn.servlet;
importjava.io.IOException;
importjava.util.List;
importjavax.servlet.ServletException;
importjavax.servlet.http.HttpServlet;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
importceet.ac.cn.dao.AdminDao;
importceet.ac.cn.model.Admin;
publicclassShowServletextendsHttpServlet{//显示全部数据
privatestaticfinallongserialVersionUID=1L;
protectedvoiddoGet(HttpServletRequestreq,HttpServletResponseresp)
throwsServletException,IOException{
this.doPost(req,resp);
}
protectedvoiddoPost(HttpServletRequestreq,HttpServletResponseresp)
throwsServletException,IOException{
AdminDaodao=newAdminDao();
List<Admin>list=dao.getAllAdmin();
req.setAttribute("list",list);
req.getRequestDispatcher("index.jsp").forward(req,resp);
}
}
packageceet.ac.cn.servlet;
importjava.io.IOException;
importjavax.servlet.ServletException;
importjavax.servlet.http.HttpServlet;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
importceet.ac.cn.dao.AdminDao;
importceet.ac.cn.model.Admin;
publicclassUpdateServletextendsHttpServlet{//修改
privatestaticfinallongserialVersionUID=1L;
protectedvoiddoGet(HttpServletRequestreq,HttpServletResponseresp)
throwsServletException,IOException{//查询到选中ID的值所对应的数据
StringidStr=req.getParameter("id");
if(idStr!=null&&!idStr.equals("")){
intid=Integer.valueOf(idStr);
AdminDaodao=newAdminDao();
Adminadmin=dao.selectAdminById(id);
req.setAttribute("admin",admin);
}
req.getRequestDispatcher("update.jsp").forward(req,resp);
}
protectedvoiddoPost(HttpServletRequestreq,HttpServletResponseresp)
throwsServletException,IOException{//根据此ID对数据的值进行修改
Stringusername=req.getParameter("username");
Stringuserpwd=req.getParameter("userpwd");
StringidStr=req.getParameter("id");
Adminadmin=newAdmin();
admin.setId(Integer.valueOf(idStr));
admin.setUsername(newString(username.getBytes("ISO-8859-1"),"UTF-8"));
admin.setUserpwd(newString(userpwd.getBytes("ISO-8859-1"),"UTF-8"));
AdminDaodao=newAdminDao();
dao.updateAdmin(admin);
req.getRequestDispatcher("ShowServlet").forward(req,resp);
}
}
<%@pagelanguage="java"import="java.util.*"pageEncoding="UTF-8"%> <!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01Transitional//EN"> <html> <head> <title>添加</title> <linkrel="stylesheet"href="css/index.css"type="text/css"/> </head> <body> <formaction="AddServlet"method="post"> <tableborder="1"class="t1"> <tr> <tdcolspan="2"><h1>添加管理员</h1></td> </tr> <tr> <td>管理员帐号:</td> <td><inputtype="text"name="username"/></td> </tr> <tr> <td>管理员密码:</td> <td><inputtype="password"name="userpwd"/></td> </tr> <tr> <tdcolspan="2"> <inputtype="submit"value="提交"/> <inputtype="reset"value="清空"/> </td> </tr> </table> </form> </body> </html>
<%@pagelanguage="java"contentType="text/html;charset=utf-8"
pageEncoding="utf-8"%>
<%@taglibprefix="c"uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPEhtmlPUBLIC"-//W3C//DTDHTML4.01Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=utf-8">
<title>显示</title>
<styletype="text/css">
table{
border:1pxsolidpink;
margin:0auto;
}
td{
width:150px;
border:1pxsolidpink;
text-align:center;
}
</style>
</head>
<body>
<table>
<tr>
<td>编号</td>
<td>帐号</td>
<td>密码</td>
<td>操作</td>
</tr>
<c:forEachitems="${list}"var="item">
<tr>
<td>${item.id}</td>
<td>${item.username}</td>
<td>${item.userpwd}</td>
<td><ahref="DeleteServlet?id=${item.id}">删除</a>|<ahref="UpdateServlet?id=${item.id}">修改</a></td>
</tr>
</c:forEach>
<tr>
<tdcolspan="6"style="text-align:left;"><ahref="add.jsp">添加管理员</a></td>
</tr>
</table>
</body>
</html>
<%@pagelanguage="java"import="java.util.*"pageEncoding="UTF-8"%>
<!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01Transitional//EN">
<html>
<head>
<title>修改</title>
<linkrel="stylesheet"href="css/index.css"type="text/css"/>
</head>
<body>
<formaction="UpdateServlet"method="post">
<tableborder="1"class="t1">
<tr>
<tdcolspan="2"><h1>修改管理员信息</h1></td>
</tr>
<tr>
<td>编号:</td>
<td><inputtype="text"name="id"value="${admin.id}"readonly="readonly"/></td>
</tr>
<tr>
<td>管理员帐号:</td>
<td><inputtype="text"name="username"value="${admin.username}"/></td>
</tr>
<tr>
<td>管理员密码:</td>
<td><inputtype="text"name="userpwd"value="${admin.userpwd}"/></td>
</tr>
<tr>
<tdcolspan="2">
<inputtype="submit"value="提交"/>
<inputtype="button"value="返回"onclick="history.go(-1)"/>
</td>
</tr>
</table>
</form>
</body>
</html>
@CHARSET"UTF-8";
table.t1{
margin-top:10px;
margin-left:20px;
margin-right:20px;
margin-bottom:5px;
#background-color:#FFF;
#background:#EEF4F9;
#border:none;
border:1;
#color:#003755;
border-collapse:collapse;
font:14px"宋体";
text-align:center;
}
table.t1th{
background:#7CB8E2;
color:#fff;
padding:6px4px;
text-align:center;
}
table.t1td{
background:#C7DDEEnonerepeat-xscrollcenterleft;
color:#000;
padding:4px2px;
}
table.t1a{
text-decoration:none;
height:1em;
}
table.t1a:link,table.t1a:visited{
color:#3366CC;
}
table.t1a:hover{
color:#B50000;
text-decoration:underline;
}
最简单的jsp+servlet的增删改查代码。写的很清楚,就这样了。
实现原理:
每行数据后面加一个编辑和删除按钮,按钮提交到后台并且带有此行数据的主要参数。
点击编辑按钮,通过servlet操作jsp将此行的每一列替换为一个文本框并把已有的值带进去,后面一个提交按钮通过submit提交数据并将文本框重新变为表格的单元格。
新增,就像编辑一样,添加一行,全部是文本框。。。
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持毛票票!