【项目实战-Java web】纯Servlet完成表单增删改查

1.准备一张数据库表

drop table if exists dept;
create table dept(
	deptno int primary key,
    dname varchar(255),
    loc varchar(255)
);
insert into dept(deptno, dname, loc) values(10, 'XiaoShouBu', 'BEIJING');
insert into dept(deptno, dname, loc) values(20, 'YanFaBu', 'SHANGHAI');
insert into dept(deptno, dname, loc) values(30, 'JiShuBu', 'GUANGZHOU');
insert into dept(deptno, dname, loc) values(40, 'MeiTiBu', 'SHENZHEN');
commit;
select * from dept;

在这里插入图片描述

2.准备一套HTML页面

欢迎页面:index.html

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
		<a href="list.html">查看部门列表</a>
	</body>
</html>

列表页面:list.html

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
		<h1 align="center">部门列表</h1>
		<hr>
		<table border="1px" align="center" width="50%">
			<tr>
				<th>序号</th>
				<th>部门列表</th>
				<th>部门名称</th>
				<th>操作</th>
			</tr>
			<tr>
				<td>1</td>
				<td>10</td>
				<td>销售部</td>
				<td>
					<a href="javascript:void(0)" onclick="window.confirm('确认删除吗?')">删除</a>
					<a href="edit.html">修改</a>
					<a href="detail.html">详情</a>
				</td>
			</tr>
			<tr>
				<td>2</td>
				<td>20</td>
				<td>研发部</td>
				<td>
					<a href="">删除</a>
					<a href="">修改</a>
					<a href="">详情</a>
				</td>
			</tr>
			<tr>
				<td>3</td>
				<td>30</td>
				<td>运营部</td>
				<td>
					<a href="">删除</a>
					<a href="">修改</a>
					<a href="">详情</a>
				</td>
			</tr>
		</table>
		<hr>
		<a href="add.html">新增部门</a>
	</body>
</html>

增加页面:add.html

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
		<h1>新增部门</h1>
		<hr>
		<form action="list.html" method="get">
			部门编号<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>

修改页面:edit.html

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
		<h1>修改部门</h1>
		<hr>
		<form action="list.html" method="get">
			部门编号<input type="text" name="deptno" value="20" readonly/><br>
			部门名称<input type="text" name="dname" value="销售部"/><br>
			部门位置<input type="text" name="loc" value="北京"/><br>
			<input type="submit" value="修改"/><br>
		</form>
	</body>
</html>

详情页面:detail.html

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>部门详情</title>
	</head>
	<body>
		<h1>部门详情</h1>
		<hr>
		部门编号:20<br>
		部门名称:销售部<br>
		部门位置:北京<br>
		<input type="button" value="后退" onclick="window.history.back()"/>
	</body>
</html>

3.功能分析

在这里插入图片描述

4.在IDEA中搭建环境

  • 创建一个app,给webapp添加servlet-api和jsp-api
  • 在webapp中添加连接数据库的jar包
  • JDBC工具类
package com.sdnu.oa.utils;

import java.sql.*;
import java.util.ResourceBundle;

/**
 * JDBC工具类
 *
 * @author Beyong
 * @date 2023/03/09 17:37
 **/
public class DBUtil {
    //静态变量,在类加载时执行
    //属性资源绑定
    private static ResourceBundle bundle = ResourceBundle.getBundle("resources.jdbc");
    //根据属性配置,获取value
    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();
        }
    }
    /**
     * 获取数据库连接对象
     * @author Beyong
     * @date 2023/03/09 17:51
     * @return java.sql.Connection
     */
    public static Connection getConnection() throws SQLException {
        Connection conn = DriverManager.getConnection(url, user, password);
        return conn;
    }

    /**
     *
     * @author Beyong
     * @date 2023/03/09 17:57
     * @param conn 连接对象
     * @param ps 数据库操作对象
     * @param rs 结果集对象
     * @return void
     */
    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();
            }
        }
    }
}
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/sdnu
user=root
password=root
  • 将所有上面的html页面拷贝到web目录下

5.功能:查看部门列表

  • 修改前端页面超链接
<!--前端超链接发送请求的时候,请求路径以"/"开始,并且带着项目名-->
<a href="/oa/dept/list">查看部门列表</a>
  • 编写web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    <servlet>
        <servlet-name>list</servlet-name>
        <servlet-class>com.sdnu.oa.web.action.DeptListServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>list</servlet-name>
        <!--web.xml文件中的这个路径也是以“/”开始的,但是不加项目名 -->
        <url-pattern>/dept/list</url-pattern>
    </servlet-mapping>
</web-app>
  • 编写 DeptListServlet类继承HttpServlet类,重写doGet方法
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

/**
 * 跳转部门列表的Servlet
 *
 * @author Beyong
 * @date 2023/03/09 18:26
 **/
public class DeptListServlet 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>部门列表页面</title>");
		out.print("	</head>");
		out.print("	<body>");
		out.print("		<h1 align='center'>部门列表</h1>");
		out.print("		<hr>");
		out.print("		<table border='1px' align='center' width='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.getConnection();
            //获取预编译的数据库操作对象
            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='')'>删除</a>");
                out.print("					<a href='edit.html'>修改</a>");
                out.print("					<a href='detail.html'>详情</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='add.html'>新增部门</a>");
        out.print("	</body>");
        out.print("</html>");

    }
}

6.功能:查看详情

  • 修改用户点击详情的地方
String contextPath = request.getContextPath();
out.print("					<a href='"+contextPath+"/dept/detail?deptno="+deptno+"'>详情</a>");
  • web.xml
    <servlet>
        <servlet-name>detail</servlet-name>
        <servlet-class>com.sdnu.oa.web.action.DeptDetailServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>detail</servlet-name>
        <!--web.xml文件中的这个路径也是以“/”开始的,但是不加项目名 -->
        <url-pattern>/dept/detail</url-pattern>
    </servlet-mapping>
  • DeptDetailServlet.java
package com.sdnu.oa.web.action;

import com.sdnu.oa.utils.DBUtil;
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 Beyong
 * @date 2023/03/10 14:02
 **/
public class DeptDetailServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

        out.print("        <!DOCTYPE html>");
        out.print("<html>");
        out.print("	<head>");
        out.print("		<meta charset='utf-8'>");
        out.print("		<title>部门详情</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.getConnection();
            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("        部门位置:北京<br>");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, ps, rs);
        }

        out.print("		<input type='button' value='后退' οnclick='window.history.back()'/>");
        out.print("	</body>");
        out.print("</html>");
    }
}

7.功能:删除部门

package com.sdnu.oa.web.action;

import com.sdnu.oa.utils.DBUtil;
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;

/**
 * 跳转部门列表的Servlet
 *
 * @author Beyong
 * @date 2023/03/09 18:26
 **/
public class DeptListServlet extends HttpServlet {
    @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("<html>");
        out.print("	<head>");
        out.print("		<meta charset='utf-8'>");
        out.print("		<title>部门列表页面</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' width='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.getConnection();
            //获取预编译的数据库操作对象
            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='edit.html'>修改</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='"+contextPath+"/add'>新增部门</a>");
        out.print("	</body>");
        out.print("</html>");
    }
}
    <servlet>
        <servlet-name>delete</servlet-name>
        <servlet-class>com.sdnu.oa.web.action.DeptDelServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>delete</servlet-name>
        <!--web.xml文件中的这个路径也是以“/”开始的,但是不加项目名 -->
        <url-pattern>/dept/delete</url-pattern>
    </servlet-mapping>

8.功能:添加部门

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></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>
package com.sdnu.oa.web.action;
import com.sdnu.oa.utils.DBUtil;
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 Beyong
 * @date 2023/03/11 12:09
 **/
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.getConnection();
            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.功能:修改部门

package com.sdnu.oa.web.action;

import com.sdnu.oa.utils.DBUtil;
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 Beyong
 * @date 2023/03/11 17:40
 **/
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.getConnection();
            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);
        }
    }
}
    <servlet>
        <servlet-name>modify</servlet-name>
        <servlet-class>com.sdnu.oa.web.action.DeptModifyServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>modify</servlet-name>
        <!--web.xml文件中的这个路径也是以“/”开始的,但是不加项目名 -->
        <url-pattern>/dept/modify</url-pattern>
    </servlet-mapping>

10.资源跳转

在这里插入图片描述

11.转发vs重定向

11.1代码上的区别

在这里插入图片描述

11.2形式上的区别

在这里插入图片描述

11.3本质上的区别

在这里插入图片描述
转发
在这里插入图片描述
重定向

在这里插入图片描述

11.4转发和重定向如何选择

在这里插入图片描述

11.5跳转的下一个资源有限制吗?必须是Servlet吗?

在这里插入图片描述

11.6 转发会存在浏览器刷新的问题

  • 3
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值