Using JDBC to Connect MySQL Database Operations to Add, Delete and Check

Keywords: Java SQL JSP Database

More wonderful content welcome to visit my personal blog Pipi Home: http://www.zhsh666.xyz or http://www.zh66.club look forward to your visit! I am Pi Pi pig. Thank you for coming. I feel very honored to be able to help you out. Wish you a happy life!

Articles Catalogue

1. First of all, the package name of Myeclipse and some implementation classes (which is my habit)

[External Link Picture Transfer Failure (img-33fh5Nqc-1567778008409)(https://cdn.jsdelivr.net/gh/Zevs6/blogimg/img/201803292248062741)]

2. Next we create a database (MySQL)

3. Add data to the database

[External Link Picture Transfer Failure (img-gaEzca3V-1567778008410)(https://cdn.jsdelivr.net/gh/Zevs6/blogimg/img/201803292305071371)]

4. First of all, BaseDao. This is the most important thing. Pay attention to the name of the database and emphasize the package name.

package dao;
 
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
 
public class BaseDao {
 
	/***
	 * 
	 * @author Database Connection Class
	 *
	 */
		private String driver ="com.mysql.jdbc.Driver";
		private String url="jdbc:mysql://localhost:3306 / table name; ----- Write the database table name by yourself, as long as the database table name is the same as here.
		private String name="Database name";      ----------Name of your own database
		private String pwd="Password";        -----------Password for your own database
	      Connection conn=null;
	      /***
	       * 
	       * @return open a connection
	       */
	    /*  public Connection getconn(){
	  		Connection conn=null;
	  		Context ctx;
	  		try {
	  			ctx = new InitialContext();
	  			DataSource ds=(DataSource)ctx.lookup("java:comp/env/jdbc/news");	
	  	    	conn=ds.getConnection();
	  		}catch (Exception e) {
	  			e.printStackTrace();
	  		}
	  		return conn;
	  	}     */
		protected  Connection getconn(){
			conn=null;	
			try {
				Class.forName(driver);
				conn=DriverManager.getConnection(url,name,pwd);
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}		
			return conn;
		}
		
		/****
		 * 
		 * @param Close database connection
		 */
		protected void closeAll(Connection conn ,PreparedStatement ps,ResultSet rs){		
			if(rs!=null)
				try {
					if(rs!=null)
					rs.close();
					if(ps!=null)
					ps.close();
					if(conn!=null)
					conn.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}				
		}
		/***
		 * 
		 * @param Addition, deletion and modification methods
		 * @param Accept parameters as SQL statements and object arrays
		 * @return Returns the number of affected rows
		 */
		public int executeUpdate(String sql ,Object []ob){
			conn=getconn();
			PreparedStatement ps=null;
			try {
				ps=prepareStatement(conn,sql,ob);
				int i=ps.executeUpdate();
				return i;	
			} catch (SQLException e) {
				// TODO Auto-generated catch block
			    //	e.printStackTrace();
				return 0;
			}finally{			
				closeAll(conn, ps, null);
			}
		
		}	
		/***
		 * Query method
		 */
		protected PreparedStatement prepareStatement(Connection conn,String sql,Object []ob){		
			PreparedStatement ps=null;
					try {
						int index=1;
						ps = conn.prepareStatement(sql);
							if(ps!=null&&ob!=null){
								for (int i = 0; i < ob.length; i++) {			
										ps.setObject(index, ob[i]);	
										index++; 
								}
							}
					} catch (SQLException e1) {
						e1.printStackTrace();
					}
			 return ps;
		}
	
}

5. This is an entity class. I believe everyone can write it. Pay attention to the package name.

package entity;
 
public class Booking {
	private int id;
	private int categoryId;
	private String title;
	private String summary;
	private String uploaduser;
	private String createdate;
	
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public int getCategoryId() {
		return categoryId;
	}
	public void setCategoryId(int categoryId) {
		this.categoryId = categoryId;
	}
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	public String getSummary() {
		return summary;
	}
	public void setSummary(String summary) {
		this.summary = summary;
	}
	public String getUploaduser() {
		return uploaduser;
	}
	public void setUploaduser(String uploaduser) {
		this.uploaduser = uploaduser;
	}
	public String getCreatedate() {
		return createdate;
	}
	public void setCreatedate(String createdate) {
		this.createdate = createdate;
	}
	
	
}

6. Next we write Booking Dao

package 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 entity.Booking;
 
public class BookingDao extends BaseDao{
	
	public List<Booking> search(String sql,Object...params){
		List<Booking> list =new ArrayList<Booking>();
		Connection conn=this.getconn();
		PreparedStatement pst=null;
		ResultSet rs=null;
		try {
			pst=this.prepareStatement(conn, sql, params);
			rs=pst.executeQuery();
			while(rs.next()){
				Booking wor=new Booking();
				wor.setId(rs.getInt(1));
				wor.setCategoryId(rs.getInt(2));
				wor.setTitle(rs.getString(3));
				wor.setSummary(rs.getString(4));
				wor.setUploaduser(rs.getString(5));
				wor.setCreatedate(rs.getString(6));
				list.add(wor);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			closeAll(conn, pst, rs);
		}
		return list;
	}
	
	//Query table
	public List<Booking> findAll(){
		String sql="SELECT * FROM `Book`";
		return search(sql);
	}
	
	//Adding Method
	public int insert(Booking t){
		String str="INSERT INTO `book`(categoryId,title,summary,uploaduser,createdate) VALUE(?,?,?,?,?)";
		return executeUpdate(str, new Object[]{t.getCategoryId(),t.getTitle(),t.getSummary(),t.getUploaduser(),t.getCreatedate()});
	}
	
	//Modification method
	public int update(Booking r){
		String sql="UPDATE `book` SET `categoryId`=?,`title`=?,`summary`=?,`uploaduser`=?,`createdate`=? WHERE id=?";
		return executeUpdate(sql, new Object[]{r.getCategoryId(),r.getTitle(),r.getSummary(),r.getUploaduser(),r.getCreatedate(),r.getId()});
	}
	
	//Delete method
	public int delete(Booking e){
		String sql="DELETE FROM `book` WHERE id=?";
		return executeUpdate(sql, new Object[]{e.getId()});
	}
	
	
}

7. Let's write Servlet

1. Servlet for queries

package servlet;
 
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import dao.BookingDao;
import entity.Booking;
 
public class selectServlet extends HttpServlet {
 
	/**
	 * Constructor of the object.
	 */
	public selectServlet() {
		super();
	}
 
	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}
 
	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
 
		doPost(request, response);
	}
 
	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
 
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		
		String opr=request.getParameter("opr");
		
	
		if(opr==null||opr.equals("list")){
			//Refresh
			BookingDao goodsDao=new BookingDao();
			List<Booking> list=goodsDao.findAll();
			request.getSession().setAttribute("list", list);
			response.sendRedirect("index.jsp");
		}
		
		
		
		
		out.flush();
		out.close();
	}
 
	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}
 
}

2. Additional Servlet

package servlet;
 
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import dao.BookingDao;
import entity.Booking;
 
public class insertServlet extends HttpServlet {
 
	/**
	 * Constructor of the object.
	 */
	public insertServlet() {
		super();
	}
 
	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}
 
	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
 
		doPost(request, response);
	}
 
	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
 
		request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		
		BookingDao rms=new BookingDao(); 
		  int categoryId=Integer.parseInt(request.getParameter("categoryId"));
		  String title=request.getParameter("title");
		  String summary=request.getParameter("summary");
		  String uploaduser=request.getParameter("uploaduser");
		  String createdate=request.getParameter("createdate");
		  Booking rm=new Booking();
			  rm.setCategoryId(categoryId);
			  rm.setTitle(title);
			  rm.setSummary(summary);
			  rm.setUploaduser(uploaduser);
			  rm.setCreatedate(createdate);
			 int i=rms.insert(rm);
			 if(i>0){
				 out.print("true");
				//Refresh
					List<Booking> listrm=rms.findAll();
					request.getSession().setAttribute("list", listrm);
			 }else{
				 out.print("false");
			 }
		
		out.flush();
		out.close();
	}
 
	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}
 
}

3. Modified Servlet

package servlet;
 
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import dao.BookingDao;
import entity.Booking;
 
public class updateServlet extends HttpServlet {
 
	/**
	 * Constructor of the object.
	 */
	public updateServlet() {
		super();
	}
 
	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}
 
	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
 
		doPost(request, response);
	}
 
	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
 
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		
		
		BookingDao booking=new BookingDao();
	    	int id=Integer.parseInt(request.getParameter("id"));
	    	 int categoryId=Integer.parseInt(request.getParameter("categoryId"));
			  String title=request.getParameter("title");
			  String summary=request.getParameter("summary");
			  String uploaduser=request.getParameter("uploaduser");
			  String createdate=request.getParameter("createdate");
			  Booking rm=new Booking();
			      rm.setId(id);
				  rm.setCategoryId(categoryId);
				  rm.setTitle(title);
				  rm.setSummary(summary);
				  rm.setUploaduser(uploaduser);
				  rm.setCreatedate(createdate);
	    	int i=booking.update(rm);
			 if(i>0){
				//Refresh
					List<Booking> listrm=booking.findAll();
					request.getSession().setAttribute("list", listrm);
					out.print("<script>alert('Successful modification!!!');location.href='index.jsp';</script>");
			 }else{
				 out.print("<script>alert('Modification failed!!!');location.href='Update.jsp';</script>");
			 }
		
		out.flush();
		out.close();
	}
 
	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}
 
}

4. Deleted Servlet

package servlet;
 
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import dao.BookingDao;
import entity.Booking;
 
public class deleteServlet extends HttpServlet {
 
	/**
	 * Constructor of the object.
	 */
	public deleteServlet() {
		super();
	}
 
	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}
 
	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
 
		doPost(request, response);
	}
 
	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
 
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		
		BookingDao rms=new BookingDao();
		Booking rm=new Booking();
		int id=Integer.parseInt(request.getParameter("id"));
		rm.setId(id);
		int i=rms.delete(rm);
		if(i>0){
			List<Booking> listrm=rms.findAll();
			request.getSession().setAttribute("list", listrm);
			out.print("<script>alert('Delete successfully!!!');location.href='index.jsp';</script>");
		}else{
			out.print("<script>alert('Delete failed!!!');location.href='index.jsp';</script>");
		}
		
		out.flush();
		out.close();
	}
 
	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}
 
}

8. Configure web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>selectServlet</servlet-name>
    <servlet-class>servlet.selectServlet</servlet-class>
  </servlet>
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>insertServlet</servlet-name>
    <servlet-class>servlet.insertServlet</servlet-class>
  </servlet>
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>updateServlet</servlet-name>
    <servlet-class>servlet.updateServlet</servlet-class>
  </servlet>
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>deleteServlet</servlet-name>
    <servlet-class>servlet.deleteServlet</servlet-class>
  </servlet>
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>idServlet</servlet-name>
    <servlet-class>servlet.idServlet</servlet-class>
  </servlet>
 
  <servlet-mapping>
    <servlet-name>selectServlet</servlet-name>
    <url-pattern>/selectServlet</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>insertServlet</servlet-name>
    <url-pattern>/insertServlet</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>updateServlet</servlet-name>
    <url-pattern>/updateServlet</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>deleteServlet</servlet-name>
    <url-pattern>/deleteServlet</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>idServlet</servlet-name>
    <url-pattern>/idServlet</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
 
</web-app>

Notice the following section, which is compared in web.xml above.

The tag declares the matching rules corresponding to the servlet, and each tag represents a matching rule. With the sum of two sub-elements, the Servlet name given by the element must be the name of the Servlet declared in the element. The element specifies the URL path corresponding to the servlet, which is the path relative to the Web application context root.

<servlet-mapping>
   <servlet-name></servlet-name>
   <url-pattern></url-pattern>
</servlet-mapping>

9. Write the JSP page again

1.index.jsp Initial Interface

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib  uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title></title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
  </head>
  
  <body>
  
  	<c:if test="${list==null}">
     <jsp:forward page="selectServlet"></jsp:forward>
    </c:if>
    <a href="insert.jsp"><input type="button" value="Additional Books"></a>
    
    <table border="1">
    	<tr><td>E-Book List</td></tr>
    	<tr><td>Book Number</td><td>Title</td><td>abstract</td><td>Uploader</td><td>Upload time</td><td>operation</td></tr>
    	<c:forEach items="${list}" var="gd">
          <tr>
          	<td>${gd.categoryId}</td>
          	<td>${gd.title}</td>
          	<td>${gd.summary}</td>
          	<td>${gd.uploaduser}</td>
          	<td>${gd.createdate }</td>
          	<td><a href="idServlet?id=${gd.id}"><input type="button" value="modify"></a></td>
          	<td><a href="deleteServlet?id=${gd.id}"><input type="button" value="delete"></a></td>
          </tr>
       </c:forEach>
    	
    </table>
  
  </body>
</html>

2.insert.jsp Add Page

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title></title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
 
	<script type="text/javascript" src="js/jquery-1.12.4.js"></script>
	<script type="text/javascript">
	$(function(){
 
           $("#submit").click(function(){
                //Non-null validation
                    var $form=$("form").serialize();
                    alert($form);
                  $.get("insertServlet",$form,function(data){
                      if(data=="true"){
                         alert("New Success");
                         window.location="index.jsp";
                      }else{
                       alert("New Failure");
                      }
                  });
       });
       });
	</script>
 
  </head>
  
  <body>
  	<form action="">
  		<h2>Additional Books</h2>
  		Book Number:<input type="text" name="categoryId"><br>
  		Book Name:<input type="text" name="title"><br>
  		abstract:<input type="text" name="summary"><br>
  		Uploader:<input type="text" name="uploaduser"><br>
  		Upload time:<input type="text" name="createdate"><br>
  		<input type="button" id="submit" value="Submission"><input type="reset" value="Reset">
  	</form>
  
  </body>
</html>

3.Update.jsp Modification Page

(1) This is the main modification.

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title></title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
 
  </head>
  
  <body>
    	<form action="updateServlet">
  		<h2>Revising Books</h2>
  		<input type="hidden" value="${idid}" name="id">
  		Book Number:<input type="text" name="categoryId"><br>
  		Book Name:<input type="text" name="title"><br>
  		abstract:<input type="text" name="summary"><br>
  		Uploader:<input type="text" name="uploaduser"><br>
  		Upload time:<input type="text" name="createdate"><br>
  		<input type="submit" id="submit" value="Submission"><input type="reset" value="Reset">
  	</form>
  </body>
</html>


(2) This idServlet is the BUG that appeared after me. Now I can only add another Servlet to it.

package servlet;
 
import java.io.IOException;
import java.io.PrintWriter;
 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
public class idServlet extends HttpServlet {
 
	/**
	 * Constructor of the object.
	 */
	public idServlet() {
		super();
	}
 
	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}
 
	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
 
		doPost(request, response);
	}
 
	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
 
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		
		int id=Integer.parseInt(request.getParameter("id"));
		request.getSession().setAttribute("idid", id);
		response.sendRedirect("Update.jsp");
		
		out.flush();
		out.close();
	}
 
	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}
 
}


10. Finally, this is the effect displayed in the browser. This is the query effect. The query table is as follows.

1. Query

[External Link Picture Transfer Failure (img-wKfi8YM4-1567778008411)(https://cdn.jsdelivr.net/gh/Zevs6/blogimg/img/201803292306105211)]

2. Increase

3. Modification (next we will modify the data we just added)

4. Delete (the effect may not be obvious, but I took a screenshot of it for the sake of the interface)

I'll delete the additions and modifications of our previous operations to see the effect!

[External Link Picture Transfer Failure (img-UJdB1eFD-1567778008412) (https://cdn.jsdelivr.net/gh/Zevs6/blogimg/img/2018032323539561)]

Well, this project has been completed, it is a complete one. Although there is Chinese random code when transferring data to the database, I will call this BUG, but at least the function has been realized. The above is the project, although in some places the effect you can see is not obvious, if this article is helpful to you. Help, please give me a compliment. Thank you. If you have any questions about this article or want me to show you step by step, add me QQQ3506346737 (Note: CSDN blog + QQ name). I am looking forward to your friend's application. I also look forward to some suggestions for improvement of this article. Thank you.

Attached source code to get the download address: Baidu Disk. When you encounter problems after downloading the code, contact me and correct the mistakes as soon as possible.

Link: https://pan.baidu.com/s/1nlOSG10a0dW72qeeUKrS2g
Extraction code: ycqr

Posted by IndianaRogers on Fri, 06 Sep 2019 07:10:08 -0700