最简单的jsp+servlet的增删改查代码
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<Admin> getAllAdmin(){ //查询所有信息
List<Admin> list = new ArrayList<Admin>(); //创建集合
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<Admin> 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"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>添加</title>
<link rel="stylesheet" href="css/index.css" type="text/css" />
</head> <body>
<form action="AddServlet" method="post">
<table border="1" class="t1">
<tr>
<td colspan="2"><h1>添加管理员</h1></td>
</tr>
<tr>
<td>管理员帐号:</td>
<td><input type="text" name="username"/></td>
</tr>
<tr>
<td>管理员密码:</td>
<td><input type="password" name="userpwd"/></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="提交"/>
<input type="reset" value="清空"/>
</td>
</tr>
</table>
</form>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>显示</title>
<style type="text/css">
table {
border: 1px solid pink;
margin: 0 auto;
} td{
width: 150px;
border: 1px solid pink;
text-align: center;
}
</style>
</head>
<body>
<table>
<tr>
<td>编号</td>
<td>帐号</td>
<td>密码</td>
<td>操作</td>
</tr>
<c:forEach items="${list}" var="item">
<tr>
<td>${item.id }</td>
<td>${item.username }</td>
<td>${item.userpwd }</td>
<td><a href="DeleteServlet?id=${item.id }">删除</a>|<a href="UpdateServlet?id=${item.id }">修改</a></td>
</tr>
</c:forEach>
<tr>
<td colspan="6" style="text-align: left;"><a href="add.jsp">添加管理员</a></td>
</tr>
</table>
</body>
</html>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>修改</title>
<link rel="stylesheet" href="css/index.css" type="text/css" />
</head> <body>
<form action="UpdateServlet" method="post">
<table border="1" class="t1">
<tr>
<td colspan="2"><h1>修改管理员信息</h1></td>
</tr>
<tr>
<td>编号:</td>
<td><input type="text" name="id" value="${admin.id}" readonly="readonly"/></td>
</tr> <tr>
<td>管理员帐号:</td>
<td><input type="text" name="username" value="${admin.username}"/></td>
</tr>
<tr>
<td>管理员密码:</td>
<td><input type="text" name="userpwd" value="${admin.userpwd}"/></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="提交"/>
<input type="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.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提交数据并将文本框重新变为表格的单元格。
新增,就像编辑一样,添加一行,全部是文本框。。。
版权声明:本文为博主原创文章,未经博主允许不得转载。
最简单的jsp+servlet的增删改查代码的更多相关文章
- jsp+servlet+mysql增删改查
用的IntelliJ IDEA开发的,jdk1.8 1 首先是项目结构,如下图所示 2看各层的代码 首先是web.xml <?xml version="1.0" encodi ...
- 四种简单的sql语句(增删改查语句)
四种简单的sql语句(增删改查语句) 一.插入语句 insert into [table] ([column],[column],[column]) values(?,?,?) 二.删除语句 dele ...
- Redis简单的数据操作(增删改查)
#Redis简单的数据操作(增删改查): 字符串类型 string 1. 存储: set key value 127.0.0.1:6379> set username zhangsan OK 2 ...
- java DMO及增删改查代码的自动生成
在web开发过程中,尤其是后台管理系统的开发中,少不了增删改成的基础操作,原来我自己的做法是一份一份的拷贝粘贴,然后修改其中的不同,然而这样既枯燥无味又浪费了大量的时间,所以根据自己项目结构的特点写了 ...
- 使用jdbc实现简单的mvc模式的增删改查
Mvc模式设计: 视图:添加界面(addUser.jsp),修改界面(updateUser.jsp),显示页面(allUser.jsp) 控制器:添加信息控制器(AddUserServlet),修改信 ...
- 一个Servlet处理增删改查的方法
处理的思路是在servlet中定义不同的增删改查方法,页面请求 的时候携带请求的参数,根据参数判断调用不同的方法. package cn.xm.small.Servlet; import java.i ...
- c#winform简单实现Mysql数据库的增删改查的语句
通过简单的SQL语句实现对数据库的增删改查. 窗口如下: 定义打开与关闭连接函数,方便每次调用: 增加指令: 删除指令: 修改指令: 查找指令: 表格情况:
- 简单实现 nodejs koa2 mysql 增删改查 制作接口
1.首先 在电脑上安装 nodejs (此处略过) 2.全局安装 koa2 (这里使用的淘宝镜像cnpm,有兴趣的同学可以自行搜索下) cnpm install koa-generator -g 3. ...
- 使用Servlet编写增删改查
第一步创建一个表 1 create database liyongzhendb default character set utf8 collate utf8_bin; 2 3 CREATE TABL ...
随机推荐
- TodoMVC中的Backbone+MarionetteJS+RequireJS例子源码分析之一
Marionette牵线木偶,Backbone是脊骨的意思,Marionette是基于Backbone做扩展库,可以理解为把脊骨骨架绑线扯着变成牵线木偶动起来哈哈,使backbone更易使用呵呵! 构 ...
- 怎样看懂Oracle的执行计划
怎样看懂Oracle的执行计划 一.什么是执行计划 An explain plan is a representation of the access path that is taken when ...
- 【UE4游戏开发】安装UE4时报SU-PQR1603错误的解决方法
马三在开发过程中一直用的都是UE4.9版本(很久没有更新了.),因为功能都够用,所以也懒得去更新.这不最近UE4 发布了最新的4.14版本,本来想尝个鲜,试试新版的UE引擎怎么样,结果这一安装上就一直 ...
- Node.js实现CORS跨域资源共享
什么是CORS CORS(Cross-origin resource sharing),跨域资源共享,是一份浏览器技术的规范,用来避开浏览器的同源策略 简单来说就是解决跨域问题的除了jsonp外的另一 ...
- KnockoutJS:
一.ko对象 js对象的改变都会导致viewmodel的变化,但view不一定变化 往ko对象里面push,viewmodel的变化,引起view的变化. 往js对象里面push,model的变化引起 ...
- 使用 SVN Hook 实现服务器端代码自动更新
之前的做法是客户端提交代码之后,再去服务器端项目中 svn up 一下来更新代码,让服务器端的项目更新到最新版本.可以编写一个 post-commit 钩子脚本来实现服务器端代码的自动更新,它在 SV ...
- asp.net core项目发布网站时的选项
发布网站时的选项 Debug 通常称为调试版本,它包含调试信息,并且不作任何优化,便于程序员调试程序. Release 称为发布版本,它往往是进行了各种优化,使得程序在代码大小和运行速度上都是最优的, ...
- swfit-计时器
import UIKit class FourVC: UIViewController { var label:UILabel = UILabel() var index : Int = var ti ...
- PHP用星号隐藏部份用户名、身份证、IP、手机号等实例
PHP用星号隐藏部份用户名.身份证.IP.手机号等实例 http://www.jb51.net/article/48800.htm 作者: 字体:[增加 减小] 类型:转载 时间:2014-04-08 ...
- java使用poi包将数据写入Excel表格
1.Excel相关操作代码 import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundExcept ...