jsp+servlet realizes the simplest code sharing of addition deletion modification and search
- 2021-11-14 06:38:54
- OfStack
Not much to say, please look at the code
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(){ // Query all information
List<Admin> list = new ArrayList<Admin>(); // Create a collection
Connection conn = DbHelper.getConnection();
String sql = "select * from admin"; //SQL Query statement
try {
PreparedStatement pst = conn.prepareStatement(sql);
ResultSet rst = pst.executeQuery();
while (rst.next()) {
Admin admin = new Admin();
admin.setId(rst.getInt("id")); // Get ID
admin.setUsername(rst.getString("username"));
admin.setUserpwd(rst.getString("userpwd"));
list.add(admin);
}
rst.close(); // Shut down
pst.close(); // Shut down
} catch (SQLException e) {
e.printStackTrace(); // Throw an exception
}
return list; // Return 1 Set of
}
public boolean addAdmin(Admin admin){ // Add information
String sql = "INSERT INTO `admin`(`id`,`username`,`userpwd`) VALUES (?,?,?)"; // Added SQL Statement
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; // Judgment of whether to add or not
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
public boolean updateAdmin(Admin admin){ // Modify
String sql = "UPDATE `admin` SET `username`=?,`userpwd`=? WHERE `id` = ?"; // Modified SQL Statement, based on the ID Modify
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()); // On the basis of ID
int count = pst.executeUpdate();
pst.close(); // Shut down
return count>0?true:false; // Judgment of whether to modify or not
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
public boolean deleteAdmin(int id){ // Delete
String sql = "delete from admin where id = ?"; // Deleted SQL Statement, based on the ID Delete
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; // Judgment of whether to delete or not
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
public Admin selectAdminById(int id){ // According to ID Make a query
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; // Return
}
}
package ceet.ac.cn.dao;
import java.sql.Connection;
import java.sql.DriverManager;
/**
* Connect to a database
* @author Draw a boat and listen to the rain and sleep
*
*/
public class DbHelper {
private static String url = "jdbc:mysql://localhost:3306/admin"; // Database address
private static String userName = "root"; // Database user name
private static String passWord = "359129127"; // Database password
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) { // Test whether the database is connected
System.err.println(getConnection());
}
}
package ceet.ac.cn.model;
import java.io.Serializable;
public class Admin implements Serializable{ // Data encapsulation class
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{ // Add data
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")); // Convert value, Chinese needs to be converted to 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{ // Delete data
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"); // Object for deleting data ID , according to ID Delete
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{ // Show all data
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{ // Modify
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException { // Query to selected ID Data corresponding to the value of
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 { // According to this ID Modify the value of the data
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> Add </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> Add Administrator </h1></td>
</tr>
<tr>
<td> Administrator account :</td>
<td><input type="text" name="username"/></td>
</tr>
<tr>
<td> Administrator password :</td>
<td><input type="password" name="userpwd"/></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value=" Submit "/>
<input type="reset" value=" Empty "/>
</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> Display </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> Numbering </td>
<td> Account number </td>
<td> Password </td>
<td> Operation </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 }"> Delete </a>|<a href="UpdateServlet?id=${item.id }"> Modify </a></td>
</tr>
</c:forEach>
<tr>
<td colspan="6" style="text-align: left;"><a href="add.jsp"> Add Administrator </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> Modify </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> Modify administrator information </h1></td>
</tr>
<tr>
<td> Numbering :</td>
<td><input type="text" name="id" value="${admin.id}" readonly="readonly"/></td>
</tr>
<tr>
<td> Administrator account :</td>
<td><input type="text" name="username" value="${admin.username}"/></td>
</tr>
<tr>
<td> Administrator password :</td>
<td><input type="text" name="userpwd" value="${admin.userpwd}"/></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value=" Submit "/>
<input type="button" value=" Return " onclick="history.go(-1)"/>
</td>
</tr>
</table>
</form>
</body>
</html>
package ceet.ac.cn.dao;
import java.sql.Connection;
import java.sql.DriverManager;
/**
* Connect to a database
* @author Draw a boat and listen to the rain and sleep
*
*/
public class DbHelper {
private static String url = "jdbc:mysql://localhost:3306/admin"; // Database address
private static String userName = "root"; // Database user name
private static String passWord = "359129127"; // Database password
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) { // Test whether the database is connected
System.err.println(getConnection());
}
}
0
The simplest jsp + servlet addition, deletion and modification of the code. It's clearly written, and that's it.
Implementation principle:
Each row of data is followed by an edit and delete button, which is submitted to the background with the main parameters of the row of data.
Click the edit button, and through servlet operation jsp, replace each column of this row with a text box and bring the existing value in. The next one submit button submits the data through submit and changes the text box into a cell of the table again.
Add, just like editing 1, add 1 line, all text boxes. . .