博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
最简单的jsp+servlet的增删改查代码
阅读量:5047 次
发布时间:2019-06-12

本文共 12530 字,大约阅读时间需要 41 分钟。

package ceet.ac.cn.dao;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.util.ArrayList;import java.util.List;import ceet.ac.cn.model.Admin;public class AdminDao {    public List
getAllAdmin(){ //查询所有信息 List
list = new ArrayList
(); //创建集合 Connection conn = DbHelper.getConnection(); String sql = "select * from admin"; //SQL查询语句 try { PreparedStatement pst = conn.prepareStatement(sql); ResultSet rst = pst.executeQuery(); while (rst.next()) { Admin admin = new Admin(); admin.setId(rst.getInt("id")); //得到ID admin.setUsername(rst.getString("username")); admin.setUserpwd(rst.getString("userpwd")); list.add(admin); } rst.close(); //关闭 pst.close(); //关闭 } catch (SQLException e) { e.printStackTrace(); //抛出异常 } return list; //返回一个集合 } public boolean addAdmin(Admin admin){ //添加信息 String sql = "INSERT INTO `admin`(`id`,`username`,`userpwd`) VALUES (?,?,?)"; //添加的SQL语句 Connection conn = DbHelper.getConnection(); try { PreparedStatement pst = conn.prepareStatement(sql); pst.setInt(1, admin.getId()); pst.setString(2, admin.getUsername()); pst.setString(3, admin.getUserpwd()); int count = pst.executeUpdate(); pst.close(); return count>0?true:false; //是否添加的判断 } catch (SQLException e) { e.printStackTrace(); } return false; } public boolean updateAdmin(Admin admin){ //修改 String sql = "UPDATE `admin` SET `username`=?,`userpwd`=? WHERE `id` = ?"; //修改的SQL语句,根据ID修改 Connection conn = DbHelper.getConnection(); try { PreparedStatement pst = conn.prepareStatement(sql); pst.setString(1, admin.getUsername()); pst.setString(2, admin.getUserpwd()); pst.setInt(3, admin.getId()); //根据的ID int count = pst.executeUpdate(); pst.close(); //关闭 return count>0?true:false; //是否修改的判断 } catch (SQLException e) { e.printStackTrace(); } return false; } public boolean deleteAdmin(int id){ //删除 String sql = "delete from admin where id = ?"; //删除的SQL语句,根据ID删除 Connection conn = DbHelper.getConnection(); try { PreparedStatement pst = conn.prepareStatement(sql); pst.setInt(1, id); int count = pst.executeUpdate(); pst.close(); return count>0?true:false; //是否删除的判断 } catch (SQLException e) { e.printStackTrace(); } return false; } public Admin selectAdminById(int id){ //根据ID进行查询 Connection conn = DbHelper.getConnection(); String sql = "select * from admin where id = "+id; Admin admin = null; try { PreparedStatement pst = conn.prepareStatement(sql); ResultSet rst = pst.executeQuery(); while (rst.next()) { admin = new Admin(); admin.setId(rst.getInt("id")); admin.setUsername(rst.getString("username")); admin.setUserpwd(rst.getString("userpwd")); } rst.close(); pst.close(); } catch (SQLException e) { e.printStackTrace(); } return admin; //返回 }}
package ceet.ac.cn.dao;import java.sql.Connection;import java.sql.DriverManager;/** * 连接数据库 * @author 画船听雨眠 * */public class DbHelper {    private static String url = "jdbc:mysql://localhost:3306/admin";  //数据库地址    private static String userName = "root";  //数据库用户名    private static String passWord = "359129127";  //数据库密码    private static Connection conn = null;        private DbHelper(){            }        public static Connection getConnection(){        if(null == conn){            try {                Class.forName("com.mysql.jdbc.Driver");                conn = DriverManager.getConnection(url, userName, passWord);            } catch (Exception e) {                e.printStackTrace();            }        }        return conn;    }        public static void main(String[] args) {  //测试数据库是否连通        System.err.println(getConnection());    }}
package ceet.ac.cn.model;import java.io.Serializable;public class Admin implements Serializable{  //数据封装类        private static final long serialVersionUID = 1L;        private int id;    private String username;    private String userpwd;        public int getId() {        return id;    }    public void setId(int id) {        this.id = id;    }    public String getUsername() {        return username;    }    public void setUsername(String username) {        this.username = username;    }    public String getUserpwd() {        return userpwd;    }    public void setUserpwd(String userpwd) {        this.userpwd = userpwd;    }    }
package ceet.ac.cn.servlet;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import ceet.ac.cn.dao.AdminDao;import ceet.ac.cn.model.Admin;public class AddServlet extends HttpServlet{  //添加数据    private static final long serialVersionUID = 1L;    protected void doGet(HttpServletRequest req, HttpServletResponse resp)            throws ServletException, IOException {        this.doPost(req, resp);    }    protected void doPost(HttpServletRequest req, HttpServletResponse resp)            throws ServletException, IOException {        String username = req.getParameter("username");        String userpwd = req.getParameter("userpwd");        Admin admin = new Admin();        admin.setUsername(new String(username.getBytes("ISO-8859-1"),"UTF-8"));  //转值,中文需要转换为utf-8        admin.setUserpwd(new String(userpwd.getBytes("ISO-8859-1"),"UTF-8"));        AdminDao dao = new AdminDao();        dao.addAdmin(admin);        req.getRequestDispatcher("ShowServlet").forward(req, resp);    }    }
package ceet.ac.cn.servlet;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import ceet.ac.cn.dao.AdminDao;public class DeleteServlet extends HttpServlet{  //删除数据    private static final long serialVersionUID = 1L;    protected void doGet(HttpServletRequest req, HttpServletResponse resp)            throws ServletException, IOException {        this.doPost(req, resp);    }    protected void doPost(HttpServletRequest req, HttpServletResponse resp)            throws ServletException, IOException {        String idStr = req.getParameter("id");  //删除数据的ID,根据ID删除        if(idStr != null && !idStr.equals("")){            int id = Integer.valueOf(idStr);            AdminDao dao = new AdminDao();            dao.deleteAdmin(id);        }        req.getRequestDispatcher("ShowServlet").forward(req, resp);    }        }
package ceet.ac.cn.servlet;import java.io.IOException;import java.util.List;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import ceet.ac.cn.dao.AdminDao;import ceet.ac.cn.model.Admin;public class ShowServlet  extends HttpServlet{  //显示全部数据    private static final long serialVersionUID = 1L;    protected void doGet(HttpServletRequest req, HttpServletResponse resp)            throws ServletException, IOException {        this.doPost(req, resp);    }    protected void doPost(HttpServletRequest req, HttpServletResponse resp)            throws ServletException, IOException {        AdminDao dao = new AdminDao();        List
list = dao.getAllAdmin(); req.setAttribute("list", list); req.getRequestDispatcher("index.jsp").forward(req, resp); } }
package ceet.ac.cn.servlet;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import ceet.ac.cn.dao.AdminDao;import ceet.ac.cn.model.Admin;public class UpdateServlet extends HttpServlet{  //修改    private static final long serialVersionUID = 1L;    protected void doGet(HttpServletRequest req, HttpServletResponse resp)            throws ServletException, IOException {  //查询到选中ID的值所对应的数据        String idStr = req.getParameter("id");        if(idStr != null && !idStr.equals("")){            int id = Integer.valueOf(idStr);            AdminDao dao = new AdminDao();            Admin admin = dao.selectAdminById(id);            req.setAttribute("admin", admin);        }        req.getRequestDispatcher("update.jsp").forward(req, resp);            }    protected void doPost(HttpServletRequest req, HttpServletResponse resp)            throws ServletException, IOException {  //根据此ID对数据的值进行修改        String username = req.getParameter("username");        String userpwd = req.getParameter("userpwd");        String idStr = req.getParameter("id");        Admin admin = new Admin();        admin.setId(Integer.valueOf(idStr));        admin.setUsername(new String(username.getBytes("ISO-8859-1"),"UTF-8"));        admin.setUserpwd(new String(userpwd.getBytes("ISO-8859-1"),"UTF-8"));        AdminDao dao = new AdminDao();        dao.updateAdmin(admin);        req.getRequestDispatcher("ShowServlet").forward(req, resp);    }        }
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>          添加    

添加管理员

管理员帐号:
管理员密码:
<%@ page language="java" contentType="text/html; charset=utf-8"    pageEncoding="utf-8"%><%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
显示
编号 帐号 密码 操作
${item.id } ${item.username } ${item.userpwd } 删除|修改
添加管理员
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>          修改    

修改管理员信息

编号:
管理员帐号:
管理员密码:
@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.t1 th{                background:#7CB8E2;                color:#fff;                padding:6px 4px;                text-align:center;        }        table.t1 td{                background:#C7DDEE none repeat-x scroll center left;                color:#000;                padding:4px 2px;        }        table.t1 a{                text-decoration:none;                height:1em;        }        table.t1 a:link, table.t1  a:visited{                color:#3366CC;        }        table.t1  a:hover{                color:#B50000;                text-decoration:underline;        }

最简单的jsp+servlet的增删改查代码。写的很清楚,就这样了。

 

实现原理: 

每行数据后面加一个编辑和删除按钮,按钮提交到后台并且带有此行数据的主要参数。 
点击编辑按钮,通过servlet操作jsp将此行的每一列替换为一个文本框并把已有的值带进去,后面一个提交按钮通过submit提交数据并将文本框重新变为表格的单元格。 
新增,就像编辑一样,添加一行,全部是文本框。。。 

 

版权声明:本文为博主原创文章,未经博主允许不得转载。

转载于:https://www.cnblogs.com/ceet/p/6213265.html

你可能感兴趣的文章
lnamp完整版[linux+apache2.4+php5.6.6+mysql5.6]
查看>>
Codeforces 620E(线段树+dfs序+状态压缩)
查看>>
Windows7中双击py文件运行程序
查看>>
Market entry case
查看>>
bzoj1230 开关灯 线段树
查看>>
LinearLayout
查看>>
学习python:day1
查看>>
css3动画属性
查看>>
第九次团队作业-测试报告与用户使用手册
查看>>
Equal Sides Of An Array
查看>>
CentOS笔记-用户和用户组管理
查看>>
Mongodb 基本命令
查看>>
MySQL 性能优化技巧
查看>>
Qt中QTableView中加入Check列实现
查看>>
“富豪相亲大会”究竟迷失了什么?
查看>>
控制文件的备份与恢复
查看>>
返回代码hdu 2054 A==B?
查看>>
Flink独立集群1
查看>>
iOS 8 地图
查看>>
20165235 第八周课下补做
查看>>