javaweb小项目,实现一个部门的增删改查功能,纯Servlet实现,完整功能代码。

1.项目结构图
在这里插入图片描述
2.数据库表结构图
在这里插入图片描述

3.DBUtil 数据库工具类

/*
 * Copyright (c) 2020, 2021,great-sun  https://blog.csdn.net/weixin_44728473 All rights reserved.
 *
 */
package org;
import java.sql.*;
import java.util.Locale;
import java.util.ResourceBundle;
import static java.sql.DriverManager.getConnection;
/**
 * @author great-sun [https://blog.csdn.net/weixin_44728473]
 */
public class DBUtil {
    Locale locale;
    //静态变量:在类加载时执行
    //并且是有顺序的。自上而下的顺序
    private static ResourceBundle bundle = ResourceBundle.getBundle("resources.jdbc");
    private static String driver =bundle.getString("driver");
    private static  String url= bundle.getString("url");
    private static  String user= bundle.getString("user");
    private static  String password= bundle.getString("password");

static{
    //注册驱动(注册驱动只需要注册一次,放在静态代码快中,DButil类加载的时候执行)
    try {
        //注册驱动
        Class.forName(driver);
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
}
    public static Connection getConnnection() throws SQLException {
   //获取连接
    Connection conn= DriverManager.getConnection(url,user,password);
   return conn;
        }
    /**
     * 释放资源
     * @param conn 连接对象
     * @param ps 数据库连接对象
     * @param rs  结果集对象
     */
        public  static void close(Connection conn, Statement ps, ResultSet rs){
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (ps != null) {
                try {
                    ps.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        }

4.jdbc.properties 连接数据库资源

driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/bjpowernode
user=root
password=

5.web.xml 配置文件

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="https://jakarta.ee/xml/ns/jakartaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee https://jakarta.ee/xml/ns/jakartaee/web-app_5_0.xsd"
         version="5.0">
    <!--部门列表-->
    <servlet>
        <servlet-name>list</servlet-name>
        <servlet-class>org.DeptListServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>list</servlet-name>
        <url-pattern>/dept/list</url-pattern>
    </servlet-mapping>

    <!--    部门详情-->
    <servlet>
        <servlet-name>detail</servlet-name>
        <servlet-class>org.DeptDetailServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>detail</servlet-name>
        <url-pattern>/dept/detail</url-pattern>
    </servlet-mapping>

    <!--    删除部门-->
    <servlet>
        <servlet-name>delete</servlet-name>
        <servlet-class>org.DeptDelServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>delete</servlet-name>
        <url-pattern>/dept/delete</url-pattern>
    </servlet-mapping>

    <!--    添加部门-->
    <servlet>
        <servlet-name>save</servlet-name>
        <servlet-class>org.DeptSaveServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>save</servlet-name>
        <url-pattern>/dept/save</url-pattern>
    </servlet-mapping>

<!--    跳转到修改部门信息页-->
    <servlet>
        <servlet-name>edit</servlet-name>
        <servlet-class>org.DeptEditServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>edit</servlet-name>
        <url-pattern>/dept/edit</url-pattern>
    </servlet-mapping>

    <!--    修改部门信息页-->
    <servlet>
        <servlet-name>modify</servlet-name>
        <servlet-class>org.DeptModifyServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>modify</servlet-name>
        <url-pattern>/dept/modify</url-pattern>
    </servlet-mapping>
</web-app>

6.DeptListServlet 部门列表

/*
 * Copyright (c) 2020, 2021,great-sun  https://blog.csdn.net/weixin_44728473 All rights reserved.
 *
 */
package org;
//jakarta是tomcat10
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author great-sun [https://blog.csdn.net/weixin_44728473]
 */
public class DeptListServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
       //设置响应的内容类型以及字符集,防止中文乱码问题
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
       //获取应用的根路径
        String contextpath = request.getContextPath();

        out.print(" <!DOCTYPE html>");
        out.print(" <head>");
        out.print("     <meta charset='utf-8'>");
        out.print("     <title>Document</title>");
        out.print("<script type='text/javascript'>");
        out.print("function del(dno){");
        out.print("if(window.confirm('亲,删了不可恢复哦!')){");
        out.print("document.location.href='" + contextpath + "/dept/delete?deptno='+dno");
        out.print("}");
        out.print("}");
        out.print("</script>");

        out.print(" </head>");
        out.print(" <body>");
        out.print("     <h1 align='center'>部门列表</h1>");
        out.print("     <hr>");
        out.print("     <table border='1px' align='center' with='50%'>");
        out.print("         <tr>");
        out.print("             <th>序号</th>");
        out.print("             <th>部门编号</th>");
        out.print("             <th>部门名称</th>");
        out.print("             <th>操作</th>");
        out.print("         </tr>");
//连接数据库,查询所有的部门
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            //获取连接
            conn = DBUtil.getConnnection();
            //获取预编译的数据库操作对象
            String sql = "select deptno as a ,dname,loc from dept";
            ps = conn.prepareStatement(sql);
            //执行SQL语句
            rs = ps.executeQuery();
            int i = 0;
            //处理结果集
            while (rs.next()) {
                String deptno = rs.getString("a");
                String dname = rs.getString("dname");
                String loc = rs.getString("loc");
                out.print("<tr>");
                out.print("           <td>" + (++i) + "</td>");
                out.print("           <td>" + deptno + "</td>");
                out.print("           <td>" + dname + "</td>");
                out.print("           <td>");
                out.print("               <a href='javascript:void(0)' οnclick='del(" + deptno + ")'>删除</a>");
                out.print("               <a href='" + contextpath + "/dept/edit?deptno=" + deptno + "'>修改</a>");
                out.print("               <a href='" + contextpath + "/dept/detail?deptno=" + deptno + "'>详情</a>");
                out.print("           </td>");
                out.print("       </tr>");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            //释放资源
            DBUtil.close(conn, ps, rs);
        }
        out.print("</table>");
        out.print(" <hr>");
        out.print("<a href='/oa/add.html'>新增部门</a>");
    }
}

7.DeptDetailServlet 部门详情

/*
 * Copyright (c) 2020, 2021,great-sun  https://blog.csdn.net/weixin_44728473 All rights reserved.
 *
 */
package org;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Parameter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author great-sun [https://blog.csdn.net/weixin_44728473]
 */
public class DeptDetailServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html; charset=utf-8");
        PrintWriter out = response.getWriter();

out.print("      <!DOCTYPE html >" );
out.print("<html> " );
        out.print("<head >" );
        out.print("  <meta charset = 'UTF-8' >" );
        out.print("  <title > Document </title >" );

        out.print("</head >" );
        out.print("<body >" );
        out.print("  <h1 > 部门详情 </h1 >" );
        out.print("  <hr >" );

        String deptno = request.getParameter("deptno");
        //连接数据库,查询所有的部门
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;

        try {
            conn = DBUtil.getConnnection();
            String sql = "select dname ,loc from dept where deptno=?";
            ps = conn.prepareStatement(sql);
            ps.setString(1, deptno);
            rs = ps.executeQuery();
            //这个结果集一定只有一条记录
            if (rs.next()) {
                String dname = rs.getString("dname");
                String loc = rs.getString("loc");

                out.print("  部门编号:"+deptno+"  <br>" );
                out.print("  部门名称: "+dname+"   <br>");
                out.print("  部门位置: "+loc+"    <br>" );
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, ps, rs);
        }
        out.print("  <input type = 'button' value = '后退' onclick = 'window.history.back()' >" );
        out.print("</body >" );
        out.print("</html >" );
    }
}

8.DeptDelServlet 删除部门

/*
 * Copyright (c) 2020, 2021,great-sun  https://blog.csdn.net/weixin_44728473 All rights reserved.
 *
 */
package org;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author great-sun [https://blog.csdn.net/weixin_44728473]
 */
public class DeptDelServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
      String deptno=request.getParameter("deptno");
       Connection conn=null;
       PreparedStatement ps=null;
       int count=0;
        try {
            conn =DBUtil.getConnnection();
           //开启事物(自动提交机制关闭)
            conn.setAutoCommit(false);
            String sql="delete from dept where deptno=?";
            ps=conn.prepareStatement(sql);
            ps.setString(1,deptno);
           //返回值是:影响了数据库表中多少条记录
            count =ps.executeUpdate();
            //事物提交
            conn.commit();
        } catch (SQLException e) {
            if (conn != null) {
                try {
                    //遇到异常回滚
                    conn.rollback();
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            }
            e.printStackTrace();
        }finally {
            DBUtil.close(conn,ps,null);
        }
       //判断删除成功还是失败
        if (count == 1) {
           //删除成功;任然跳转到部门列表页面;
           //转发
            request.getRequestDispatcher("/dept/list").forward(request,response);
        }else{
            //删除失败
            request.getRequestDispatcher("/error.html").forward(request,response);
        }
    }
}

DeptSaveServlet 添加部门

/*
 * Copyright (c) 2020, 2021,great-sun  https://blog.csdn.net/weixin_44728473 All rights reserved.
 *
 */
package org;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * @author great-sun [https://blog.csdn.net/weixin_44728473]
 */
public class DeptSaveServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      request.setCharacterEncoding("utf-8");
      String deptno=request.getParameter(("deptno"));
      String dname=request.getParameter(("dname"));
      String loc=request.getParameter(("loc"));

      Connection conn=null;
      PreparedStatement ps=null;
      int count=0;
        try {
            conn=DBUtil.getConnnection();
            String sql ="insert into dept(deptno,dname,loc) values(?,?,?)";
            ps=conn.prepareStatement(sql);
            ps.setString(1,deptno);
            ps.setString(2,dname);
            ps.setString(3,loc);
            count=ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DBUtil.close(conn,ps,null);
        }

        if (count == 1) {
            //保存成功跳到列表页面
            //转发是一次请求
            request.getRequestDispatcher("/dept/list").forward(request,response);
        }else{
            //保存失败跳转到错误页面
            request.getRequestDispatcher("/error.html").forward(request,response);
        }
    }
}

9.DeptEditServlet 展示要修改部门的信息

/*
 * Copyright (c) 2020, 2021,great-sun  https://blog.csdn.net/weixin_44728473 All rights reserved.
 *
 */
package org;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author great-sun [https://blog.csdn.net/weixin_44728473]
 */
public class DeptEditServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String contextPath=request.getContextPath();
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        out.print("     <!DOCTYPE html>");
        out.print("<html lang='en'>");
        out.print("<head>");
        out.print("    <meta charset='UTF-8'>");
        out.print("    <title>Document</title>");
        out.print("</head>");
        out.print("<body>");
        out.print("    <h1>修改部门</h1>");
        out.print("    <hr>");
        out.print("    <form action='"+contextPath+"/dept/modify' method='post'>");
        //获取部门编号
        String deptno = request.getParameter("deptno");
        //连接数据库,根据部门编号查询部门的信息
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            conn = DBUtil.getConnnection();
            String sql = "select dname, loc as location from dept where deptno=?";
            ps=conn.prepareStatement(sql);
            ps.setString(1, deptno);
            rs = ps.executeQuery();
            //这个结果集中只有一条记录。
            if (rs.next()) {
                String dname = rs.getString("dname");
                String location = rs.getString("location");//location 是查询结果列的列名。
               //输出动态网页
                out.print("  部门编号<input type='text' name='deptno' value='"+deptno+"' readonly ><br>");
                out.print("  部门名称<input type='text' name='dname' value='"+dname+"' ><br>");
                out.print("  部门位置<input type='text' name='loc' value='"+location+"'  ><br>");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, ps, rs);
        }
        out.print(" <input type='submit' value='修改'/><br>");
        out.print(" </form>");
        out.print("</body>");
        out.print("</html>");
    }
}

10.DeptModifyServlet 修改部门操作

/*
 * Copyright (c) 2020, 2021,great-sun  https://blog.csdn.net/weixin_44728473 All rights reserved.
 *
 */
package org;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * @author great-sun [https://blog.csdn.net/weixin_44728473]
 */
public class DeptModifyServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //解决请求体的中文乱码问题
        request.setCharacterEncoding("utf-8");
        //获取表单中的数据
        String deptno = request.getParameter("deptno");
        String dname = request.getParameter("dname");
        String loc = request.getParameter("loc");
        //连接数据库执行更新语句
        Connection conn = null;
        PreparedStatement ps = null;
        int count = 0;
        try {
            conn = DBUtil.getConnnection();
            String sql = "update dept set dname=?,loc=? where deptno=?";
            ps = conn.prepareStatement(sql);
            ps.setString(1, dname);
            ps.setString(2, loc);
            ps.setString(3, deptno);
            count = ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, ps, null);
        }
        if (count == 1)
        {
            request.getRequestDispatcher("/dept/list").forward(request,response);
        }else
        {
            request.getRequestDispatcher("/error.html").forward(request,response);
        }
    }
}

11.index.html 起始页

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <a href="/oa/dept/list">查看部门列表</a>
</body>
</html>

12.add.html 添加

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1>新增部门</h1>
    <hr>
    <form action="/oa/dept/save" method="post">
        部门编号<input type="text" name="deptno" ><br>
        部门名称<input type="text" name="dname"  ><br>
        部门位置<input type="text" name="loc"  ><br>
        <input type="submit" value="保存"/><br>
    </form>
</body>
</html>

13.error.html 报错页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>操作失败,<a href="javascript:void(0)" onclick="window.history.back()">返回</a></h1>
</body>
</html>

14.运行截图
在这里插入图片描述

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

great-sun

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值