JDBC结合JSP使用(1)

自古美人都是妖i 提交于 2020-02-17 09:40:44

1. 添加数据

在jsp页面中添加数据,和在serv中添加数据相似。获得页面中提交的数据以后,把数据保存到数据库表中,JSP的代码如下:

add.jsp

<%@ page language="java" import="java.sql.*" pageEncoding="gb2312"%>
<%
request.setCharacterEncoding("gb2312");
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>My JSP 'add.jsp' starting page</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="" method="post">
    <h1><label>请输入部门信息:</label></h1>
    <label>部门号:</label><br/>
    <input type="text" name="id"/><br/>
    <label>部门名:</label><br/>
    <input type="text" name="d_name"/><br/>
    <label>部门人数:</label><br/>
    <input type="text" name="empnumber"/><br/>
    <label>地址:</label><br/>
    <input type="text" name="address"/><br/><br/>
    <input type="submit" value="提交"/>
    </form>
  </body>
</html>
<%
    Connection conn = null;  
    PreparedStatement ps = null;
    try{
        Class.forName("com.mysql.jdbc.Driver");
        System.out.println("创建数据库驱动成功!");
        conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/bank","root","1234");
        System.out.println("数据库连接成功!");
        String sql = "insert into dept(id,d_name,address,empnumber) values(?,?,?,?)";
        ps = conn.prepareStatement(sql);
        String id = request.getParameter("id");
        String d_name = request.getParameter("d_name");
        String address = request.getParameter("address");
        int empnumber = Integer.parseInt(request.getParameter("empnumber"));
        ps.setString(1,id);
        ps.setString(2,d_name);
        ps.setString(3,address);
        ps.setInt(4,empnumber);
        int result = ps.executeUpdate();
        if(result == 1)
            out.print("插入数据成功!");
        else
            out.print("插入数据失败,请重新插入!");
        }catch(Exception e){
            out.println("无法连接数据库,请检查数据库连接是否正确!");
        }
%>

 2. 显示全部数据

在页面中显示全部数据,也就是要把数据库中的全部数据查询出来,要实现这个功能,需要用到实体类,即数据库和实体对象的映射类。实体类代码如下:

DeptVo.java

package com.cn.vo;

public class DeptVo {
    private String id;
    private String address;
    private int empnumber;
    private String d_name;
    private int d_id;
    
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    public int getEmpnumber() {
        return empnumber;
    }
    public void setEmpnumber(int empnumber) {
        this.empnumber = empnumber;
    }
    public String getD_name() {
        return d_name;
    }
    public void setD_name(String dName) {
        d_name = dName;
    }
    public int getD_id() {
        return d_id;
    }
    public void setD_id(int dId) {
        d_id = dId;
    }

}

编写好实体类型后,就可以在页面中调用该类,在JSP页面中编写JDBC,连接数据库和查询数据,再用JSTL标签库中的c标签遍历输出数据,使用EL表达式取值。JSP中的代码如下:

showAll.jsp

<%@ page language="java" import="java.util.*" pageEncoding="gb2312"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page import="com.cn.vo.*" %>
<%@ page import="java.sql.*" %>
<%
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>My JSP 'showAll.jsp' starting page</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>
  <%
  List<DeptVo> list = new ArrayList<DeptVo>();
  try{
      Class.forName("com.mysql.jdbc.Driver");
      Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/bank","root","1234");
      Statement stmt = con.createStatement();
      ResultSet rs = stmt.executeQuery("SELECT * FROM dept");
      while(rs.next()){
          DeptVo deptVo = new DeptVo();
          deptVo.setId(rs.getString("id"));
          deptVo.setAddress(rs.getString("address"));
          deptVo.setD_id(rs.getInt("d_id"));
          deptVo.setD_name(rs.getString("d_name"));
          deptVo.setEmpnumber(rs.getInt("empnumber"));
          list.add(deptVo);
          }
      request.setAttribute("list",list); //把list集合放入request对象中
      }catch(Exception e){
          e.printStackTrace();
      }
   %>
  <body>
    <table border="1" align="center" width="70%">
        <tr>
            <td>部门编号</td>
            <td>部门地址</td>
            <td>部门人数</td>
            <td>部门名称</td>
            <td>部门id</td>
        </tr>
        <c:forEach items="${list}" var="list">
        <tr>
            <td>${list.id }</td>
            <td>${list.address }</td>
            <td>${list.empnumber }</td>
            <td>${list.d_name }</td>
            <td>${list.d_id }</td>
        </tr>
        </c:forEach>
    </table>
  </body>
</html>

 3. 显示单条数据信息

显示单条信息就是根据数据的唯一标示符来查询出单条数据的详细信息。在dept表中,主键d_id的值是自动增长的,不会有重复,可以根据d_id查询出单条数据信息。首先要在页面中输入要查询的d_id值,然后根据d_id来查询数据的详细信息。输入查询条件的JSP文件代码如下:

item.jsp

<%@ page language="java" import="java.util.*" pageEncoding="gb2312"%>
<%
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>My JSP 'item.jsp' starting page</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="ShowById.jsp" method="post">
        <label>请输入部门id:</label><br/><br/>
        <input type="text" name="d_id"/><br/><br/>
        <input type="submit" value="查找"/>
    </form>
  </body>
</html>

显示在同一页面中的ShowById.jsp文件的代码如下:

<%@ page language="java" import="java.util.*" pageEncoding="gb2312"%>
<%@ page import="com.cn.vo.*" %>
<%@ page import="java.sql.*" %>
<%@page import="javax.servlet.jsp.tagext.TryCatchFinally"%>
<%
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>My JSP 'ShowById.jsp' starting page</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>
  <%
      int d_id = Integer.parseInt(request.getParameter("d_id"));
      Connection con = null;
      PreparedStatement pstmt = null;
      ResultSet rs = null;
      try{
          Class.forName("com.mysql.jdbc.Driver");
          System.out.println("创建驱动成功!");
          con = DriverManager.getConnection("jdbc:mysql://localhost:3306/bank","root","1234");
          System.out.println("数据库连接成功!");
          String sql = "select * from dept where d_id =?";
          pstmt = con.prepareStatement(sql);
          pstmt.setInt(1,d_id);
          rs = pstmt.executeQuery();
          while(rs.next()){
              DeptVo deptVo = new DeptVo();
              deptVo.setId(rs.getString("id"));
              deptVo.setAddress(rs.getString("address"));
              deptVo.setD_id(rs.getInt("d_id"));
              deptVo.setD_name(rs.getString("d_name"));
              deptVo.setEmpnumber(rs.getInt("empnumber"));
              request.setAttribute("deptVo",deptVo);
              System.out.println(deptVo.getD_id());
              }
          }catch(Exception e){
              e.printStackTrace();
          }
   %>
  <body>
    <jsp:include flush="true" page="item.jsp"></jsp:include>
    <hr/>
    <h2>d_id值为<%=d_id%>的数据详细信息</h2>
        <table border="1" align="center" width="70%">
            <tr>
                <td>部门编号</td>
                <td>部门地址</td>
                <td>部门人数</td>
                <td>部门名称</td>
                <td>部门id</td>
            </tr>
            <tr>
                <td>${deptVo.id }</td>
                <td>${deptVo.address }</td>
                <td>${deptVo.empnumber }</td>
                <td>${deptVo.d_name }</td>
                <td>${deptVo.d_id }</td>
            </tr>
        </table>
  </body>
</html>

 4. 修改数据

修改数据的时候,要把修改的数据信息显示到页面中,然后在页面中根据实际情况来修改数据,修改数据成功后,数据库会保存修改后的数据。

先编写输入修改数据条件的页面,代码如下:

updateItem.jsp

<%@ page language="java" import="java.util.*" pageEncoding="gb2312"%>
<%
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>My JSP 'updateItem.jsp' starting page</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="queryToUpdate.jsp" method="post">
        <label>请输入部门id:</label><br/><br/>
        <input type="text" name="d_id"/><br/><br/>
        <input type="submit" value="查找"/>
    </form>
  </body>
</html>

上述代码中,form表单的action值是queryToUpdate.jsp,当提交查询时,会打开queryToUpdate.jsp页面,在queryToUpdate.jsp页面中查询出的d_id指向的数据信息,并显示到页面中。queryToUpdate.jsp页面代码如下:

<%@ page language="java" import="java.util.*" pageEncoding="gb2312"%>
<%@ page import="com.cn.vo.*" %>
<%@ page import="java.sql.*" %>
<%
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>My JSP 'queryToUpdate.jsp' starting page</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>
    <%
        response.setCharacterEncoding("gb2312");
        request.setCharacterEncoding("gb2312");
        Connection con = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try{
            int d_id = Integer.parseInt(request.getParameter("d_id"));
            Class.forName("com.mysql.jdbc.Driver");
            System.out.println("创建驱动成功!");
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/bank","root","1234");
            System.out.println("数据库连接成功!");
            String sql = "select * from dept where d_id=?";
            ps = con.prepareStatement(sql);
            ps.setInt(1,d_id);
            rs = ps.executeQuery();
            while(rs.next()){
                DeptVo deptVo = new DeptVo();
                deptVo.setAddress(rs.getString("address"));
                deptVo.setD_id(rs.getInt("d_id"));
                deptVo.setD_name(rs.getString("d_name"));
                deptVo.setEmpnumber(rs.getInt("empnumber"));
                deptVo.setId(rs.getString("id"));
                request.setAttribute("deptVo",deptVo);
                System.out.println(deptVo.getD_id());
                }
            }catch(Exception e){
                e.printStackTrace();
            }
     %>
     <form action="update.jsp" method="post">
         <h1><label>请输入部门信息:</label></h1>
         <label>部门号:</label><br/>
         <input type="text" name="id" value="${deptVo.id}"/><br/>
         <label>部门名:</label><br/>
         <input type="text" name="d_name" value="${deptVo.d_name}"/><br/>
         <label>部门人数:</label><br/>
         <input type="text" name="empnumber" value="${deptVo.empnumber}"/><br/>
         <label>地址:</label><br/>
         <input type="text" name="address" value="${deptVo.address}"/><br/>
         <label>部门id:</label><br/>
         <input type="text" name="d_id" value="${deptVo.d_id}"/><br/><br/>
         <input type="submit" value="修改"/>
     </form>
  </body>
</html>

页面效果如下所示:

在上面的页面中提交修改后,会打开form表单action指定的update.jsp页面,在该页面中处理数据修改,并包含了输入修改条件的页面。update.jsp代码如下:

<%@ page language="java" import="java.util.*" pageEncoding="gb2312"%>
<%@ page import="java.sql.*" %>
<%
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>My JSP 'update.jsp' starting page</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>
  <%
      response.setCharacterEncoding("gb2312");
      request.setCharacterEncoding("gb2312");
      Connection con = null;
      PreparedStatement ps = null;
      String id = request.getParameter("id");
      String address = request.getParameter("address");
      int empnumber = Integer.parseInt(request.getParameter("empnumber"));
      String d_name = request.getParameter("d_name");
      int d_id = Integer.parseInt(request.getParameter("d_id"));
      try{
          Class.forName("com.mysql.jdbc.Driver");
          System.out.println("数据库驱动创建成功!");
          con = DriverManager.getConnection("jdbc:mysql://localhost:3306/bank","root","1234");
          System.out.println("数据库连接成功!");
          String sql = "update dept set id=?,address=?,empnumber=?,d_name=?,d_id=? where d_id=?";
          ps = con.prepareStatement(sql);
          ps.setString(1,id);
          ps.setString(2,address);
          ps.setInt(3,empnumber);
          ps.setString(4,d_name);
          ps.setInt(5,d_id);
          ps.setInt(6,d_id);
          ps.executeUpdate();
          out.println("<h1>修改成功!</h1>");
          }catch(Exception e){
              e.printStackTrace();
          }    
   %>
  <body>
    <jsp:include flush='true' page='updateItem.jsp'></jsp:include>
  </body>
</html>

程序运行后界面如下:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!