对于利用JavaBean+Servlet+jsp实现增删改查功能题目的实现
阅读原文时间:2023年07月08日阅读:3

首先,为了更好地规范代码,可以分别将不同用处的Java文件放置到不同的文件夹里面

具体的实现方法如下:

//mainBean.java
public class mainBean{
private String name;
private String id;
private String teacher;
private String whe;
public void setName(String name){
this.name=name;
}
public String getName(){
return name;
}
public void setId(String id){
this.id=id;
}
public String getId(){
return id;
}
public void setTeacher(String teacher){
this.teacher=teacher;
}
public String getTeacher(){
return teacher;
}
public void setWhe(String whe){
this.whe=whe;
}
public String getWhe(){
return whe;
}
public mainBean(){}
public mainBean(String name,String id,String teacher,String whe){
this.name=name;
this.id=id;
this.teacher=teacher;
this.whe=whe;
}

封装数据库的连接操作时,可以选择使用JDBC连接,也可以使用db.properties进行连接,在这里示范的是后者

//db.properties
driver=com.mysql.cj.jdbc.Driver
url=jdbc:/mysql://localhost:3306/数据库名称
username=用户名
pass=密码

需要注意到的是,有时db文件里面的url需要加上时区等内容,否则就会报错!

//DBUtil.java
package DBUtils;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class DBUtil {
    private static String driver;
    private static String url;
    private static String username;
    private static String pass;

    static{
        InputStream is=DBUtil.class.getClassLoader().getResourceAsStream("db.properties");

        Properties p=new Properties();
        try{
            p.load(is);
            driver=p.getProperty("driver");
            url=p.getProperty("url");
            username=p.getProperty("username");
            pass=p.getProperty("pass");

            Class.forName(driver);
            System.out.println("驱动注册成功!");

        } catch (IOException | ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    public static Connection getConn() throws SQLException {
        Connection conn=null;
        conn= DriverManager.getConnection(url,username,pass);
        System.out.println("数据库连接成功!");
        return conn;
    }

    public static void close(PreparedStatement ps,Connection conn) throws SQLException {
        if(ps!=null){
            ps.close();
        }
        if(conn!=null){
            conn.close();
        }
    }

    public static void close(Statement stmt,Connection conn) throws SQLException {
        if(stmt!=null){
            stmt.close();
        }
        if(conn!=null){
            conn.close();
        }
    }

    public static void close(PreparedStatement ps,Connection conn,ResultSet rs) throws SQLException {
        if(rs!=null){
            rs.close();
        }
        if(ps!=null){
            ps.close();
        }
        if(conn!=null){
            conn.close();
        }
    }
}


//interDao.java
package Dao;

import Bean.mainBean;

import java.sql.SQLException;
import java.util.List;

public interface interDao {
    boolean addMain(mainBean bean) throws SQLException;

    List<mainBean> searchMain(String name) throws SQLException;

    boolean updateMain(mainBean main) throws SQLException;

    boolean deleteMain(String name) throws SQLException;
}



//getDao.java
package Dao;

import Bean.mainBean;
import DBUtils.DBUtil;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class getDao implements interDao{

    private static final String sql_insert="insert into we values(?,?,?,?)";
    private static final String sql_delete="delete from we where name=?";
    private static final String sql_update="update we set id=?,teacher=?,whe=? where name=?";
    private static final String sql_search="select * from we where name=?";

    @Override
    public boolean addMain(mainBean main) throws SQLException {

        Connection conn= null;
        PreparedStatement ps=null;
        try {
            conn = DBUtil.getConn();
            ps=conn.prepareStatement(sql_insert);
            ps.setString(1,main.getName());
            ps.setString(2,main.getId());
            ps.setString(3,main.getTeacher());
            ps.setString(4,main.getWhe());

            int x=ps.executeUpdate();

            return x>0?true:false;

        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally{
            DBUtil.close(ps,conn);
        }

    }

    @Override
    public List<mainBean> searchMain(String name) throws SQLException {
        List<mainBean> list=new ArrayList<mainBean>();
        Connection conn=DBUtil.getConn();
        PreparedStatement ps=null;
        ResultSet rs=null;
        try{
            ps=conn.prepareStatement(sql_search);
            ps.setString(1,name);
            rs=ps.executeQuery();
            while(rs.next()){
                mainBean main=new mainBean();
                main.setName(rs.getString("name"));
                main.setId(rs.getString(1));
                main.setTeacher(rs.getString(2));
                main.setWhe(rs.getString(3));

                list.add(main);
            }

        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally{
            DBUtil.close(ps,conn,rs);
        }
        return null;
    }

    @Override
    public boolean updateMain(mainBean main) throws SQLException {
        Connection conn=DBUtil.getConn();
        PreparedStatement ps=null;
        try{
            ps=conn.prepareStatement(sql_update);
            ps.setString(1,main.getId());
            ps.setString(2,main.getTeacher());
            ps.setString(3,main.getWhe());
            ps.setString(4,main.getName());

            int x=ps.executeUpdate();
            return x>0?true:false;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally{
            DBUtil.close(ps,conn,null);
        }
    }

    @Override
    public boolean deleteMain(String name) throws SQLException {
        Connection conn=DBUtil.getConn();
        PreparedStatement ps=null;
        try{
            ps=conn.prepareStatement(sql_delete);
            ps.setString(1,name);

            int x=ps.executeUpdate();
            return x>0?true:false;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally{
            DBUtil.close(ps,conn);
        }
    }
}



//mainServlet.java
package Servlet;

import Bean.mainBean;
import Dao.getDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/mainServlet")
public class mainServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;//使得兼容性更强一些

    getDao gg=new getDao();

    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
         req.setCharacterEncoding("utf-8");

             String method=req.getParameter("method");

             try {
                 if ("searchMain".equals(method)) {
                     searchMain(req, resp);
                 } else if ("addMain".equals(method)) {
                     addMain(req, resp);
                 } else if ("updateMain".equals(method)) {
                     updateMain(req, resp);
                 } else if ("deleteMain".equals(method)) {
                     deleteMain(req, resp);
                 }
             } catch (SQLException e) {
                 e.printStackTrace();
             }
    }

    public mainServlet(){ super(); }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //super.doPost(req, resp);
        doGet(req, resp);

    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.getWriter().append("Served at:").append(req.getContextPath());
    }

    private void searchMain(HttpServletRequest req, HttpServletResponse resp) throws IOException, SQLException, ServletException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");

        String name=req.getParameter("name");

        Connection conn= DBUtil.getConn();
        PreparedStatement psmt=null;
        ResultSet rs=null;

        psmt=conn.prepareStatement("select * from we where name=?");
        psmt.setString(1,name);
        rs=psmt.executeQuery();
        while(rs.next()){
            req.setAttribute("name",rs.getString("name"));
            req.setAttribute("id",rs.getString("id"));
            req.setAttribute("teacher",rs.getString("teacher"));
            req.setAttribute("whe",rs.getString("whe"));
            req.getRequestDispatcher("check2.jsp").forward(req,resp);
        }

        DBUtil.close(psmt,conn,rs);

    }

    private void addMain(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, SQLException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");

        String name=req.getParameter("name");
        String id=req.getParameter("id");
        String teacher=req.getParameter("teacher");
        String whe=req.getParameter("whe");

        mainBean main=new mainBean();
        main.setName(name);
        main.setId(id);
        main.setTeacher(teacher);
        main.setWhe(whe);

        if(gg.addMain(main)){
            req.setAttribute("main",main);
            req.setAttribute("name","添加成功!");
            req.getRequestDispatcher("search.jsp").forward(req,resp);
        }else{
            req.setAttribute("name","添加失败!");
            req.getRequestDispatcher("index.jsp").forward(req,resp);
        }
    }

    protected void updateMain(HttpServletRequest req, HttpServletResponse resp) throws IOException, SQLException, ServletException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");

        String name=req.getParameter("name");
        String id=req.getParameter("id");
        String teacher=req.getParameter("teacher");
        String whe=req.getParameter("whe");

        mainBean main=new mainBean();
        main.setName(name);
        main.setId(id);
        main.setTeacher(teacher);
        main.setWhe(whe);

        if(gg.updateMain(main)){
            req.setAttribute("name","修改成功!");
            req.getRequestDispatcher("search.jsp").forward(req,resp);
        }else{
            req.setAttribute("name","修改失败!");
            req.getRequestDispatcher("update.jsp").forward(req,resp);
        }

    }

    protected void deleteMain(HttpServletRequest req, HttpServletResponse resp) throws IOException, SQLException, ServletException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");

        String name=req.getParameter("name");

        if(gg.deleteMain(name)){
            req.setAttribute("name","删除成功!");
            req.getRequestDispatcher("search.jsp").forward(req,resp);
        }else{
            req.setAttribute("name","删除失败!");
            req.getRequestDispatcher("delete.jsp").forward(req,resp);
        }
    }
}



//Main.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>主界面</title>
</head>
<body>
<center>
    <tr>
        <button type="submit" value="添加" onclick="window.location.href='index.jsp'">添加信息</button>
    </tr>
    <p>
    <tr>
        <button type="submit" value="修改" onclick="window.location.href='update.jsp'">修改信息</button>
    </tr>
    <p>
    <tr>
        <button type="submit" value="删除" onclick="window.location.href='delete.jsp'">删除信息</button>
    </tr>
    <p>
    <tr>
        <button type="submit" value="浏览" onclick="window.location.href='search.jsp'">浏览信息</button>
    </tr>
    <p>
    <tr>
        <button type="submit" value="查询" onclick="window.location.href='check1.jsp'">查询信息</button>
    </tr>
</center>
</body>
</html>


//check1.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>查询界面</title>
</head>
<body>
<center>
    <form action="mainServlet?method=searchMain" method="post">
        <h1>查询</h1>
        <tr>
            <input type="text" name="name" id="name" placeholder="请输入你想要查询的学生姓名">
        </tr>
        <p>
            <tr>
                <button type="submit" value="查询">查询</button>
            </tr>
    </form>

</center>
</body>
</html>


//check2.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>显示界面</title>
</head>
<body>
<center>
    <form>
        <tr>
            <td>学生姓名</td>
            <td>学生学号</td>
            <td>教师姓名</td>
            <td>授课地点</td>
        </tr>
        <p>
        <tr>
            <td>${name}</td>
            <td>${id}</td>
            <td>${teacher}</td>
            <td>${whe}</td>
        </tr>
    </form>
</center>
</body>
</html>


//index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>添加界面</title>
  </head>
  <body>
  <center>
    <form action="mainServlet?method=addMain" method="post">
      <table>
        <tr>
          <td>学生姓名:</td>
          <td><input type="text" name="name" id="name" placeholder="请输入学生姓名" required></td>
        </tr>
        <p>
        <tr>
          <td>学生学号:</td>
          <td><input type="text" name="id" id="id" placeholder="请输入学生学号:" required></td>
        </tr>
        <p>
        <tr>
          <td>教师姓名:</td>
          <td><input type="text" name="teacher" id="teacher" placeholder="请输入教师姓名:" required></td>
        </tr>
        <p>
        <tr>
          <td>授课地点:</td>
          <td><input type="text" name="whe" id="whe" placeholder="请输入授课地点:" required></td>
        </tr>
        <p>
      </table>
      <tr>
        <button type="submit" value="提交">提交</button>
      </tr>
    </form>
  </center>
  </body>
</html>


//search.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>浏览界面</title>
</head>
<body>
<center>
    <tr>
        <th scope="col"> 学生姓名 </th>
        <th scope="col"> 学生学号 </th>
        <th scope="col"> 教师姓名 </th>
        <th scope="col"> 授课地点 </th>
    </tr>
    <p>
    <%
        Class.forName("com.mysql.cj.jdbc.Driver");

        Connection conn= DriverManager.getConnection("jdbc:mysql://localhost:3306/ad?useUnicode=true&characterEncoding=utf-8","root","20214063");
        Statement ps=conn.createStatement();
        ResultSet rs=ps.executeQuery("select * from we");

        while(rs.next()){
            out.println(" <tr> <th scope=row > " + rs.getString(1) + " </th><td> "+ rs.getString(2) + " </td><td> " + rs.getString(3) + " </td><td> " + rs.getString(4) + " </td></tr><p> ");
        }
        rs.close();
        ps.close();
        conn.close();
    %>
</center>
</body>
</html>


//delete.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>删除界面</title>
</head>
<body>
<center>
  <form action="mainServlet?method=deleteMain" method="post">
      <table>
          <h1>删除</h1>
          <tr>
              <td>学校姓名:</td>
              <td><input type="text" name="name" id="name" placeholder="请输入你想要删除的学生姓名:"></td>
          </tr>
      </table>
      <p>
      <button type="submit" value="提交">删除</button>
  </form>
</center>
</body>
</html>

咳咳,update.jsp代码与index.jsp代码基本一致,只需要改一改action里面的值就可以啦!就不写出来了

本次内容仅仅提供代码进行参考,对界面是否漂亮并没有做出要求!!!

手机扫一扫

移动阅读更方便

阿里云服务器
腾讯云服务器
七牛云服务器

你可能感兴趣的文章