使用JDBC连接MySQL数据库操作增删改查(非常详细,适合学习,欢迎转载)

news/2024/5/18 23:11:25 标签: Servlet, JSP, JDBC, Java, myeclipse

目录

       1.首先这个Myeclipse的包名以及一些实现的类(这样子写是我的习惯)

          2.接下来我们创建数据库(MySQL)

        3.在数据库里面添加数据

        4.首先是BaseDao,这个是重中之重,注意那个数据库的名字,强调所在的包名

      5.这个是实体类,我相信大家都会写,注意所在的包名,注意所在的包名注意所在的包名,重要的事情所三遍

        6.接下来我们写BookingDao

        

Servlet-toc" style="margin-left:0px;">    7.下面我们写Servlet

Servlet-toc" style="margin-left:80px;">        1.查询的Servlet

Servlet-toc" style="margin-left:80px;">        2.添加的Servlet

Servlet-toc" style="margin-left:80px;">        3.修改的Servlet

Servlet-toc" style="margin-left:80px;">        4.删除的Servlet

JSP%E9%A1%B5%E9%9D%A2-toc" style="margin-left:0px;">        8.再次写JSP页面

              1.index.jsp 初始界面

              2.insert.jsp 添加页面    

              3.Update.jsp 修改页面

     9. 最后这个是在浏览器中显示的效果,这个是查询效果,查询全表如下

           1.查询

         2.增加

         3.修改(接下里我们把刚才我们添加的数据修改)

         4.删除(这个效果可能不是很明显,但为了界面我还是把它给截图下来了)


  

       1.首先这个Myeclipse的包名以及一些实现的类(这样子写是我的习惯)

      

          2.接下来我们创建数据库(MySQL)

          

         

 

        3.在数据库里面添加数据

         

        4.首先是BaseDao,这个是重中之重,注意那个数据库的名字,强调所在的包名

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 数据库连接类
	 *
	 */
		private String driver ="com.mysql.jdbc.Driver";
		private String url="jdbc:mysql://localhost:3306/表名";        ---------自己写数据库表名,只要数据库的表名跟这里的一样就行
		private String name="数据库名称";      ----------你自己数据库的名称
		private String pwd="密码";        -----------你自己数据库的密码
	      Connection conn=null;
	      /***
	       * 
	       * @return 打开连接
	       */
	    /*  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 关闭数据库连接
		 */
		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 增删改方法
		 * @param 接受 参数为 SQL语句 和 对象数组
		 * @return 返回受影响行数
		 */
		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);
			}
		
		}	
		/***
		 * 查询方法
		 */
		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.这个是实体类,我相信大家都会写,注意所在的包名

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.接下来我们写BookingDao

        

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;
	}
	
	//查询表
	public List<Booking> findAll(){
		String sql="SELECT * FROM `Book`";
		return search(sql);
	}
	
	//添加方法
	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()});
	}
	
	//修改方法
	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()});
	}
	
	//删除方法
	public int delete(Booking e){
		String sql="DELETE FROM `book` WHERE id=?";
		return executeUpdate(sql, new Object[]{e.getId()});
	}
	
	
}

Servlet">    7.下面我们写Servlet

Servlet">        1.查询的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 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")){
			//刷新
			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
	}

}

 

Servlet">        2.添加的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");
				//刷新
					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
	}

}

 

Servlet">        3.修改的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){
				//刷新
					List<Booking> listrm=booking.findAll();
					request.getSession().setAttribute("list", listrm);
					out.print("<script>alert('修改成功!!!');location.href='index.jsp';</script>");
			 }else{
				 out.print("<script>alert('修改失败!!!');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
	}

}

 

Servlet">        4.删除的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('删除成功!!!');location.href='index.jsp';</script>");
		}else{
			out.print("<script>alert('删除失败!!!');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.配置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>

 需要注意的是下面段,在上面是web.xml中比较下面,

<servlet-mapping>标签声明了与该servlet相应的匹配规则,每个<url-pattern>标签代表1个匹配规则。含了两个子元素<servlet- name>和<url-pattern>,<servlet-name>元素给出的Servlet名字必须是 在<servlet>元素中声明过的Servlet的名字。<url-pattern>元素指定对应于Servlet的URL路 径,该路径是相对于Web应用程序上下文根的路径。

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

 

JSP%E9%A1%B5%E9%9D%A2">        9.再次写JSP页面

              1.index.jsp 初始界面

   

<%@ 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="新增图书"></a>
    
    <table border="1">
    	<tr><td>电子图书列表</td></tr>
    	<tr><td>书品编号</td><td>书名</td><td>摘要</td><td>上传人</td><td>上传时间</td><td>操作</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="修改"></a></td>
          	<td><a href="deleteServlet?id=${gd.id}"><input type="button" value="删除"></a></td>
          </tr>
       </c:forEach>
    	
    </table>
  
  </body>
</html>

 

              2.insert.jsp 添加页面    

                  

<%@ 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(){
                //非空验证
                    var $form=$("form").serialize();
                    alert($form);
                  $.get("insertServlet",$form,function(data){
                      if(data=="true"){
                         alert("新增成功");
                         window.location="index.jsp";
                      }else{
                       alert("新增失败");
                      }
                  });
       });
       });
	</script>

  </head>
  
  <body>
  	<form action="">
  		<h2>新增书本</h2>
  		书本编号:<input type="text" name="categoryId"><br>
  		书本名称:<input type="text" name="title"><br>
  		摘要:<input type="text" name="summary"><br>
  		上传人:<input type="text" name="uploaduser"><br>
  		上传时间:<input type="text" name="createdate"><br>
  		<input type="button" id="submit" value="提交"><input type="reset" value="重置">
  	</form>
  
  </body>
</html>

 

              3.Update.jsp 修改页面

                (1)这个是修改的主要

<%@ 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>修改书本</h2>
  		<input type="hidden" value="${idid}" name="id">
  		书本编号:<input type="text" name="categoryId"><br>
  		书本名称:<input type="text" name="title"><br>
  		摘要:<input type="text" name="summary"><br>
  		上传人:<input type="text" name="uploaduser"><br>
  		上传时间:<input type="text" name="createdate"><br>
  		<input type="submit" id="submit" value="提交"><input type="reset" value="重置">
  	</form>
  </body>
</html>

                (2)这个idServlet是我后面出现的BUG,我现在只能给又加了一个Servlet

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
	}

}

 

     9. 最后这个是在浏览器中显示的效果,这个是查询效果,查询全表如下

           1.查询

        

         2.增加

               

         3.修改(接下里我们把刚才我们添加的数据修改)

                

 

         4.删除(这个效果可能不是很明显,但为了界面我还是把它给截图下来了)

               我把刚才我们上面操作的添加和修改给删除掉看看效果!

              

最后,项目运行地址:http://localhost:8080/ebookentry-JDBC/index.jsp     看你的端口是808几了。

好了,这个项目也算了做完了,是个完整的,虽然在往数据库传数据的时候出现了中文乱码,但是我会去调这个BUG的,但至少功能实现了。

以上就是这个项目了,虽然在有些地方大家看到的效果不是很明显,如果本篇文章看了对大家有帮助,麻烦大家点个赞,谢谢,如果对本篇有疑问有出现报错的地方或者是其他问题,加我QQ3506346737(备注:CSDN博客+QQ名字),很期待您的好友申请,也很期待大家对本篇文章的一些改进建议,谢谢

附源码获取下载地址:百度网盘。如果连接资源不存在,也请在第一时间加QQ,捧上源码。下载代码后遇到问题及时联系本人,尽快修正错误。

链接:https://pan.baidu.com/s/1nlOSG10a0dW72qeeUKrS2g 
提取码:ycqr 

 

 

 


http://www.niftyadmin.cn/n/1303888.html

相关文章

WebStorm中文乱码解决代码

<meta http-equiv"Content-Type" content"text/html;charsetutf-8"> 以上这张图是我用HTML方式写的一张简历,好,现在运行 大家看,我运行起来的这个代码,在页面中已经中文乱码了,这个问题之前一直困扰着我,前几天刚刚得到了解决方法,现在分享给大家. …

jsp页面开头报错解决办法

很多人在创建jsp完都会遇到如下的错误&#xff0c;贼几把烦&#xff0c;我也是被逼无奈很多次遇到过这种错误&#xff0c;第一次的遇到的时候我还不知道怎么搞。 虽然对于功能是可以实现&#xff0c;但是看着jsp页面报错就感觉很不舒服。 报错代码&#xff1a; <% page l…

使用SSM框架实现增删改查

springmvc的理解:https://blog.csdn.net/qq_41879385/article/details/82885516本项目的jsp页面使用bootstrap前端框架&#xff1a;https://blog.csdn.net/qq_41879385/article/details/82431238编译器eclipse&#xff0c;数据库MySQL5.5.25&#xff0c;jdk1.8&#xff0c;tomc…

鼠标点击网页出现爱心特效

像这样的鼠标点击网页出现js的特效&#xff0c;代码如下&#xff0c;只需要直接把这段代码复制到<script></script>标签下运行就可以实现了&#xff0c;要导入css和js&#xff1a; //鼠标点击出现爱心特效(function(window,document,undefined){var hearts [];win…

大话西游:人生百年,谁不曾大闹天宫,谁不曾头上紧箍,谁不曾爱上层楼,谁不曾孤单上路。...

周星驰在1995年上映的大话西游&#xff0c;刚开始看的时候可以笑的没心没肺&#xff0c;感觉很搞笑&#xff0c;但是在不知不觉的几年的爱情世故&#xff0c;有时候都会觉得曾经的爱情多么的纯真&#xff0c;很多年后在回头看看大话西游不知不觉就流泪了。 紫霞喜欢至尊宝&…

oracle 11g安装教程

第一步&#xff1a;电子邮件可以写&#xff0c;也可以不写都没关系&#xff0c;取消“我希望通过My Oracle Support接受安全更新(W)”。 下一步&#xff1a;点击“是” 第二步&#xff1a;选择“创建和配置数据库”&#xff0c;单击“下一步” 第三步&#xff1a;选择桌面类。然…

用git将本地项目上传至GitHub

困扰了许久的骚操作&#xff0c;后来就莫名其妙的上去了GitHub&#xff0c;我回想了一下操作&#xff0c;整理一下&#xff0c;以便自己和大家日后的回顾。 准备工具&#xff1a;git&#xff0c;git的安装很简单&#xff0c;傻瓜式安装&#xff0c;下一步下一步&#xff0c;就不…

Unity:简单的蓄力技能的逻辑实现

先随意创建一个游戏对象用于测试 获取一下SpriteRenderer组件&#xff0c;实现不同的蓄力改变它的颜色。 private bool isDown; private float time; private SpriteRenderer spriteRenderer; void Start() {isDown false;spriteRenderer GetComponent<SpriteRenderer&…