Servlet小项目 | 基于纯Servlet手写一个单表的CRUD操作

news2024/9/21 1:29:44

使用纯粹的Servlet完成单表【对部门的】的增删改查操作。(B/S结构的)

目录

一:设计数据库表及原型

二:动态实现部门列表及详情页

三:实现部门删除功能

四:实现部门新增功能

五:实现部门修改功能


一:设计数据库表及原型

第一步:准备一张数据库表(部门表dept)

把sql语句写成一个脚本文件dept.sql!

// 先删除数据库中这张表
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;

 然后在指定的数据库中直接用 source命令+脚本文件绝对路径 即可创建dept表和插入数据!

第二步:准备一套HTML页面(项目原型)

(1)把HTML页面准备好,然后将HTML页面中的链接都能够跑通。(页面流转没问题)

(2)此时设计的页面显示的内容都是写死的,后期连接数据库会进行动态获取。

(3)应该设计的页面(模板框架)

  • 欢迎页面:welcome.html

  • 列表页面:list.html(以列表页面为核心,展开其他操作)

  • 新增页面:add.html

  • 修改页面:modify.html

  • 详情页面:look.html

注意:以下的页面都只是作为框架使用,目前都是写死的,后面会逐渐在代码中动态获取的形式!

 ①欢迎页面:welcome.html可以跳转到列表页面list.html

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>欢迎使用OA系统</title>
	</head>
	<body>
		<!-- 点击跳转到部门列页面list.html -->
		<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="">删除</a>
					<a href="modify.html">修改</a>
					<a href="detail.html">详情</a>
				</td>
			</tr>
			<tr>
				<td>2</td>
				<td>20</td>
				<td>研发部</td>
				<td>
					<!-- 执行操作跳转到对应的页面 -->
					<a href="">删除</a>
					<a href="modify.html">修改</a>
					<a href="detail.html">详情</a>
				</td>
			</tr>
			<tr>
				<td>3</td>
				<td>30</td>
				<td>运营部</td>
				<td>
					<!-- 执行操作跳转到对应的页面 -->
					<a href="">删除</a>
					<a href="modify.html">修改</a>
					<a href="detail.html">详情</a>
				</td>
			</tr>
		</table>
		<!-- 新增部门 -->
		<hr>
		<!-- 跳转到新增页面 -->
		<a href="add.html">新增部门</a>
	</body>
</html>

页面效果如下: 

③新增页面:add.html可以跳转到列表页面list.html

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>新增部门页面</title>
	</head>
	<body>
		<h1>新增部门</h1>
		<hr>
		<!-- form表单,get方式提交 -->
		<!-- 新增完提交后,返回到列表页面:list.html -->
		<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>

④修改页面:modify.html可以跳转到列表页面list.html

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>修改部门页面</title>
	</head>
	<body>
		<h1>修改部门</h1>
		<hr>
		<!-- 修改完提交后,返回到列表页面:list.html -->
		<form action="list.html" method="get">
			<!-- 以下的value实际上是动态获取的,后期会进行修改 -->
			<!-- 但是部门编号是不能修改的,加上readonly,表示只读 -->
			部门编号<input type="text" name="deptno" value="10" 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可以跳转到列表页面list.html

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>部门详情页面</title>
	</head>
	<body>
		<h1>部门详情页面</h1>
		<hr>
		部门编号:10 <br>
		部门名称:销售部<br>
		部门位置:北京<br>
		<!-- 没有表单,利用按钮进行回退到上一步 -->
		<input type="button"  value="后退"  onclick="window.history.back()"/>
	</body>
</html>

第三步:分析我们这个系统包括哪些功能

(1)功能的定义:只要这个操作连接了数据库,就表示一个独立的功能。

(2)包括了哪些功能?

  • 查看部门列表

  • 新增部门

  • 删除部门

  • 查看部门详细信息

  • 跳转到修改页面

  • 修改部门

第四步:在IDEA当中搭建开发环境

(1)创建一个webapp(给这个webapp添加servlet-api.jar和jsp-api.jar到classpath当中)

(2)向webapp中添加连接数据库的jar包(mysql驱动)

  • 必须在WEB-INF目录下新建lib目录,然后将mysql的驱动jar包拷贝到这个lib目录下。这个目录名必须叫做lib,全部小写的。

(3)编写一个JDBC的工具类,因为我们要多处使用JDBC代码,所以编写一个工具类。

(4)编写一个属性配置文件xxx.properties。

(5)将所有HTML页面拷贝到web目录下,接下来一步步替换成动态获取的方式。

属性配置文件:jdbc.properties

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/bjpowernode
username=root
password=123

JDBC工具类:DBUtil 

package com.bjpowernode.oa.utils;

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

/**
 * JDBC的工具类
 */
public class DBUtil {

    // 定义为静态变量:在类加载时执行,静态代码块和静态方法里面都需要静态变量。
    // 属性资源文件绑定,在resources包下,且不需要写“.properties”
    private static ResourceBundle bundle = ResourceBundle.getBundle("resources.jdbc");
    // 根据属性配置文件key获取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();
        }
    }

    /**
     * 获取数据库连接对象
     * @return conn 连接对象
     * @throws SQLException
     */
    public static Connection getConnection() 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();
            }
        }
    }

}

二:动态实现部门列表及详情页

第五步:实现第一个功能:查看部门列表

tips:对于一个功能的实现;可以从后端往前端一步一步写,也可以从前端一步一步往后端写。千万不要想起来什么就写什么;假设这里从前端开始,那么一定是从用户点击按钮那里开始的!

①先修改前端页面的超链接路径,因为用户先点击的就是这个超链接;这里要链接数据库,肯定要执行一段Java代码

<a href="list.html">查看部门列表</a>
<!--修改为-->
<a href="/oa/dept/list">查看部门列表</a>

②编写web.xml文件

<servlet>
    <servlet-name>list</servlet-name>
    <servlet-class>com.bjpowernode.oa.web.action.DeptListServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>list</servlet-name>
    <url-pattern>/dept/list</url-pattern>
</servlet-mapping>

③编写DeptListServlet类继承HttpServlet类,然后重写doGet方法

package com.bjpowernode.oa.web.action;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


public class DeptListServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

    }
}

④在DeptListServlet类的doGet方法中连接数据库,查询所有的部门,动态的展示部门列表页面

(1)分析list.html页面中哪部分是固定死的,哪部分是需要动态展示的。

(2)list.html页面中的内容所有的双引号要替换成单引号,因为out.print("")这里有一个双引号,容易冲突。

(3)换成动态生成的页面数据后,原来静态的list.html就可以干掉了!

package com.bjpowernode.oa.web.action;

import com.bjpowernode.oa.utils.DBUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.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:朗朗乾坤
 * @Package:com.bjpowernode.oa.web.action
 * @Project:JavaWeb
 * @name:DeptListServlet
 * @Date:2022/11/10 19:05
 */
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("	</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 {
            // 1,2. 注册驱动和获取连接
            conn = DBUtil.getCoonetion();
            // 3.获取预编译的数据库操作对象
            String sql = "select deptno,dname,loc from dept";
            ps = conn.prepareStatement(sql);
            // 4.执行sql
            rs = ps.executeQuery();
            // 处理查询结果集
            int i = 0;
            while(rs.next()){
                String deptno = rs.getString("deptno");
                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='modify.html'>修改</a>");
                out.print("					<a href='detail.html'>详情</a>");
                out.print("				</td>");
                out.print("			</tr>");
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            // 6.关闭资源
            DBUtil.close(conn,ps,rs);
        }

/*下面一部分是死的*/
        out.print("		</table>");
        out.print("		<hr >");
        out.print("		<a href='add.html'>新增部门</a>");
        out.print("	</body>");
        out.print("</html>");

    }
}

(4)最终链接数据库得到的动态页面如下:

第六步:查看部门详情

①用户点击的详情页面在“查看部门列表的”后端java代码里,需要修改一下路径;对于项目名,可以调用request.getContextPath()动态获取,然后在进行字符串拼接即可!

<a href="detail.html">详情</a>
<!--进行修改,并传入部门编号-->
<a href='"+contextPath+"/dept/detail?deptno="+deptno+"'>详情</a>");

②重点:向服务器提交数据的格式:

uri?name=value&name=value&name=value&name=value 

③写web.xml文件

<servlet>
    <servlet-name>detail</servlet-name>
    <servlet-class>com.bjpowernode.oa.web.action.DeptDetailServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>detail</servlet-name>
    <url-pattern>/dept/detail</url-pattern>
</servlet-mapping>

④编写一个类:DeptDetailServlet继承HttpServlet,重写doGet方法

(1)换成动态生成的页面数据后,原来静态的detail.html就可以干掉了!

package com.bjpowernode.oa.web.action;

import com.bjpowernode.oa.utils.DBUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.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:朗朗乾坤
 * @Package:com.bjpowernode.oa.web.action
 * @Project:JavaWeb
 * @name:DeptDetailServlet
 * @Date:2022/11/10 20:24
 */
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>部门详情</title>");
        out.print("	</head>");
        out.print("	<body>");
        out.print("		<h1>部门详情</h1>");
        out.print("		<hr >");

        // 根据deptno(key)获取value(部门编号)
        // 虽然是提交的30,但是服务器获取的是"30"这个字符串。
        String deptno = request.getParameter("deptno");

        // 连接数据库,根据部门编号查询部门信息。
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            // 1,2. 注册驱动和获取连接
            conn = DBUtil.getCoonetion();
            // 3.获取预编译的数据库操作对象
            String sql = "select dname,loc from dept where deptno = ?";
            ps = conn.prepareStatement(sql); // 先编译
            ps.setString(1, deptno); // 在给部门编号(第一个?)赋值
            // 4.执行sql
            rs = ps.executeQuery();
            // 5.处理查询结果集,这个结果集一定只有一条记录,因为deptno是主键。
            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>");
    }
}

⑤ 这样就能做到点击哪个部门的详情就显示哪个部门的内容

三:实现部门删除功能

第七步:删除部门

(1)从前端页面开始,用户点击删除按钮的时候,应该提示用户是否删除;因为删除这个动作是比较危险的。任何系统在进行删除操作之前,是必须要提示用户的,因为这个删除的动作有可能是用户误操作。(在前端页面上写JS代码,来提示用户是否删除)

(2)javascript:void(0) 表示:仍然保留住超链接的样子,点击此超链接之后,不进行页面的跳转!

(3)onclick这里表示鼠标单击事件,点击超链接时执行一个回调函数,在回调函数里发送请求!

①前端代码

<a href=''>删除</a>")
<!--修改为-->
<a href='javascript:void(0)' onclick='del("+deptno+")'>删除</a>")
<!--执行的事件-->
<script type="text/javascript">
	function del(dno){
		if(window.confirm("亲,删了不可恢复哦!")){
			document.location.href = "/oa/dept/delete?deptno=" + dno;
		}
	}
</script>

②以上的前端程序要写到后端的java代码当中:

在列表DeptListServlet类的doGet方法当中,使用out.print()方法,将以上的前端代码输出到浏览器上即可。

③写web.xml文件

<servlet>
    <servlet-name>delete</servlet-name>
    <servlet-class>com.bjpowernode.oa.web.action.DeptDelServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>delete</servlet-name>
    <url-pattern>/dept/delete</url-pattern>
</servlet-mapping>

④编写DeptDelServlet继承HttpServlet,重写doGet方法

package com.bjpowernode.oa.web.action;

import com.bjpowernode.oa.utils.DBUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * @Author:朗朗乾坤
 * @Package:com.bjpowernode.oa.web.action
 * @Project:JavaWeb
 * @name:DeptDelServlet
 * @Date:2022/11/14 14:42
 */
public class DeptDelServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/htmp;charset=UTF-8");
        PrintWriter out = response.getWriter();

        // 根据部门编号,删除部门
        // 1. 获取部门编号,根据key获取value
        String deptno = request.getParameter("deptno");
        // 2. 连接数据库
        Connection conn = null;
        PreparedStatement ps = null;
        int count = 0;
        try {
            // 注册驱动和获取连接
            conn = DBUtil.getCoonetion();
            // 获取预编译的数据库操作对象
            String sql = "delete from dept where deptno = ?";
            ps = conn.prepareStatement(sql);
            ps.setString(1,deptno);
            // 返回值是:影响了数据库当中多少数据
            // 这里根据主键删除,肯定只影响的一条
            count = ps.executeUpdate();

        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            // 关闭资源
            DBUtil.close(conn,ps,null);
        }

        //3. 判断有没有删除成功
        // 判断删除成功了还是失败了。
        if (count == 1) {
            //删除成功,仍然跳转到部门列表页面
            //部门列表页面的显示需要执行另一个Servlet。怎么办?转发。
            request.getRequestDispatcher("/dept/list").forward(request, response);
        }else{
            // 删除失败
            request.getRequestDispatcher("/error.html").forward(request, response);
        }
    }
}

⑤删除失败,跳转的页面

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

四:实现部门新增功能

第八步:新增部门

①前端代码

<a href='add.html'>新增部门</a>
<!--修改为-->
<a href='"+contextPath+"/add.html'>新增部门</a>");
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>新增部门</title>
	</head>
	<body>
		<h1>新增部门</h1>
		<hr >
        <!--<form action="list.html" method="get"-->
        <!--修改,提交数据需要post请求-->
        <!--form action="/oa/dept/add" method="post"-->
		<form action="/oa/dept/add" 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>

②写web.xml文件

<servlet>
    <servlet-name>add</servlet-name>
    <servlet-class>com.bjpowernode.oa.web.action.DeptAddServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>add</servlet-name>
    <url-pattern>/dept/add</url-pattern>
</servlet-mapping>

③编写DeptDelServlet继承HttpServlet,重写doPost方法(提交数据使用Post方式);而前面我们DeptListServlet用的都是Get请求,所以在跳转时就会出现405错误!

怎么解决?两种方案

  • 第一种:在/dept/list Servlet中添加doPost方法,然后在doPost方法中调用doGet。

  • 第二种:重定向

// 在DeptListServlet类中增加doPost方法中调用doGet方法
@Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }
package com.bjpowernode.oa.web.action;

import com.bjpowernode.oa.utils.DBUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * @Author:朗朗乾坤
 * @Package:com.bjpowernode.oa.web.action
 * @Project:JavaWeb
 * @name:DeptAddServlet
 * @Date:2022/11/14 15:58
 */
public class DeptAddServlet 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");
        // 连接数据库执行insert语句
        Connection conn = null;
        PreparedStatement ps = null;
        int count = 0;
        try {
            // 注册驱动和获取连接
            conn = DBUtil.getCoonetion();
            // 获取预编译数据库操作对象
            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);
            // 执行sql
            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);
        }


    }
}

五:实现部门修改功能

第九步:跳转到修改部门的页面

①前端代码

<a href='modify.html'>修改</a>")
<!--修改为-->
<a href='"+contextPath+"/dept/modify?deptno="+deptno+"'>修改</a>")

②写web.xml文件

    <servlet>
        <servlet-name>modify</servlet-name>
        <servlet-class>com.bjpowernode.oa.web.action.DeptModifyServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>modify</servlet-name>
        <url-pattern>/dept/modify</url-pattern>
    </servlet-mapping>

③编写DeptModifyServlet继承HttpServlet,重写doGet方法,编写连接数据库代码,进行查看

package com.bjpowernode.oa.web.action;

import com.bjpowernode.oa.utils.DBUtil;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.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:朗朗乾坤
 * @Package:com.bjpowernode.oa.web.action
 * @Project:JavaWeb
 * @name:DeptModifyServlet
 * @Date:2022/11/14 18:34
 */
public class DeptModifyServlet 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();
        // 获取部门编号
        String deptno = request.getParameter("deptno");

        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 >");
        out.print("		<form action='' method='get'>");

        // 连接数据库
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            // 注册驱动和获取连接
            conn = DBUtil.getCoonetion();
            // 获取预编译的数据库操作对象
            String sql = "select dname,loc from dept where deptno = ?";
            ps = conn.prepareStatement(sql);
            ps.setString(1, deptno);
            // 执行sql
            rs = ps.executeQuery();
            // 处理查询结果集,肯定是只有一条数据
            if (rs.next()) {
                String dname = rs.getString("dname");
                String loc = rs.getString("loc");
                // 输出到页面
                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='"+loc+"'/><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>");
    }

}

第十步:修改部门

①前端代码

向前端提交数据,肯定是使用的是post请求方式!

<form action='' method='get'>
<!--修改为-->
<form action='"+contextPath+"/dept/update' method='post'>

②写web.xml文件

    <servlet>
        <servlet-name>update</servlet-name>
        <servlet-class>com.bjpowernode.oa.web.action.DeptUpdateServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>update</servlet-name>
        <url-pattern>/dept/update</url-pattern>
    </servlet-mapping>

③编写DeptUpdateServlet继承HttpServlet,重写doPost方法,编写连接数据库代码,进行数据的修改,注意:对于主键deptno是不能修改的!

package com.bjpowernode.oa.web.action;

import com.bjpowernode.oa.utils.DBUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * @Author:朗朗乾坤
 * @Package:com.bjpowernode.oa.web.action.com.bjpowernode.oa.web.action
 * @Project:JavaWeb
 * @name:DeptUpdateServlet
 * @Date:2022/11/14 19:19
 */
public class DeptUpdateServlet 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.getCoonetion();
            // 获取预编译数据库操作对象
            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);
            // 执行sql,返回更新的条数
            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);
        }
    }
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/22000.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

NJUPT算法分析与设计期末考试2021.11.24

NJUPT算法分析与设计期末考试2021.11.24判断简答1.算法是什么&#xff1f;算法的时间复杂度是什么&#xff1f;衡量的原则&#xff0c;标准&#xff0c;工具2.分支限界法扩展活节点的方式有哪两种&#xff0c;有什么差别&#xff1f;3.回溯法搜索子集树&#xff0c;排列树的算法…

PostgreSQL下载和安装教程

PostgreSQL下载和安装嘚吧嘚下载安装配置pgAdmin设置中文安装中遇到的问题The database cluster initialisation failed.问题描述解决方法嘚吧嘚 公司在用PostgreSQL数据库&#xff0c;和MySQL一样是免费试用的。虽然不知道公司出于什么考虑没有选择MySQL&#xff0c;而是选用…

【户外】东莞-银瓶山-常规路线-登山游记+攻略

不想看流水的请直接看最后攻略 此次路线&#xff1a;北上南下。累计行走约11.57km. 2022/11/20 周日 东莞最近YQ严重&#xff0c;不是拉去Jiankang驿站&#xff0c;就是居家GeLi&#xff0c;加上工作也郁闷&#xff0c;出去走走。 昨晚两点睡觉&#xff0c;在给各种设备补电量…

qq录屏快捷键是什么?qq录屏声音设置

我们日常生活中&#xff0c;有时会突然遇到需要用电脑录制屏幕的情况&#xff0c;这个时候我们可以通过按下qq录屏的快捷键进行录屏。有些小伙伴就有疑问了&#xff0c;电脑qq录屏快捷键是什么&#xff1f; qq录屏声音如何设置&#xff1f;别急&#xff0c;接下来小编给大家详细…

SpringMVC跳转

转发&#xff1a; 1&#xff1a;添加成功跳转到成功页面&#xff0c;给出提示&#xff0c;失败跳转到失败页面 ---- jsp 2&#xff1a;添加成功后&#xff0c;跳转到查询的controller中 -- 另外一个程序&#xff0c;添加完成之后&#xff0c;执行查询所有的操作&#xff0c…

Linux环境基础开发工具使用

Linux环境基础开发工具使用 文章目录Linux环境基础开发工具使用1.Linux软件包管理器 yum1.1 什么是软件包1.2 了解rzsz(文件传输工具)1.3 查看软件包1.4 安装与卸载软件指令1.5 更新yum源2.Linux开发工具介绍2.1 vi/vim开发工具介绍2.2 vi/vim的按键图解3.Linux编辑器---vim的使…

数字信号处理 | 实验二 MATLAB z换和z逆变换分析+求解差分方程+求解单位冲击响应+求解幅频相频特性曲线+求解零极点

1.实验目的 (1)掌握离散时间信号的z变换和z逆变换分析 (2)掌握MATLAB中利用filter函数求解差分方程&#xff1b; (3)掌握MATLAB中利用impz函数求解单位冲击响应h(n); (4)掌握MATLAB中利用freqz函数求解幅频特性曲线和相频特性曲线&#xff1b; (5)掌握MATLAB中利用zplane函…

Spring事务管理 | 数据库连接池流程原理分析

&#x1f497;wei_shuo的个人主页 &#x1f4ab;wei_shuo的学习社区 &#x1f310;Hello World &#xff01; 文章目录▌Spring事务管理环境搭建标准配置声明式事务总结▌SqlSessionFactoryXML 中构建 SqlSessionFactory获得 SqlSession 的实例代码实现▌作用域&#xff08;Sco…

2022.11.20 学习周报

文章目录摘要论文阅读1.题目2.摘要3.网络结构3.1 网络示意图3.2 网络特点4.问题的提出5.正则化带有LSTM单元的RNNs5.1 LSTM单元5.2 具有 Dropout 的正则化6.实验6.1 语音建模6.2 语音识别6.3 机器翻译6.4 图像字幕生成7.结论深度学习Pytorch实现简单的RNN总结摘要 This week, …

总账科目 前台操作关事务代码及操作要点

目录 1、维护会计科目相关代码及要点 2、公司代码中的科目参数详解 1、维护会计科目相关代码及要点 事务代码&#xff1a;FSP0 在科目表中维护科目 操作例子&#xff1a;创建1001010100 现金-人民币 及40010001实收资本. 点保存后成功展示如下图 注意&#xff0c;后台必须的…

treeSelect树组件设置父节点禁用

前言&#xff1a; 项目开发中需求方提了这样一个需求&#xff1a;下拉框数据是树形结构&#xff0c;但父节点禁止点选&#xff0c;只能点击子节点。毫无疑问&#xff0c;选用的是 ant design vue 组件库的 treeSelect 组件。但该组件默认每一级节点都可以进行选择&#xff0c;…

Vagrant+VirtualBox快速搭建Linux环境

VagrantVirtualBox快速搭建Linux环境虚拟机Oracle VM VirtualBoxVMware虚拟机的选择Vagrant介绍Vagrant安装centos7虚拟机固定ip配置允许账号密码登录Xshell 连接Vagrant生成的虚拟机虚拟机 虚拟机&#xff08;Virtual Machine&#xff09;指通过软件模拟的具有完整硬件系统功…

通过docker部署grafana和mysql

1. 简介2. 网络设置 - 2.1 docker网络设置 - 2.2 防火墙设置3. MySQL - 3.1 启动MySQL - 3.2 配置mysql - 3.3 创建只读用户 - 3.4 创建数据库4. Grafana - 4.1 启动Grafana - 4.2 配置数据源 - 4.3 dashboard与panel5. 参考 1. 简介 grafana是一个数据可视化程序, 可通过浏览…

python gdal geopandas basemap cartopy安装

python彻底解决Basemap cartopy geopandas 安装问题 Basemap cartopy geopandas rasterio这几个库存在一定的依赖关系&#xff0c;由于环境的变化 很可能哪天不知道就报错了&#xff1a; 版本不一致&#xff0c;运行也可能报错&#xff0c;如GDAL3.0的主要变化在于对空间参考…

13. PyQt5实现多页面切换之QTabWidget

PyQt5实现多页面切换之QTabWidget QTabWidget 类直接继承自 QWidget。该类提供了一个选项卡栏(QTabBar)和一个相应的页面区域&#xff0c;用于显示与每个选项卡相对应的页面。 与 QStackedLayout 布局原理相同&#xff0c;只有当前页面(即可见页面)是可见的&#xff0c;所有其他…

Flutter 动态更改应用程序启动图标

Flutter 动态更改应用程序启动图标 前言 在这篇文章中&#xff0c;我们将讨论如何在运行时在我们的 flutter 应用程序中动态更改多个应用程序启动器图标。 依赖包 一个用于动态更改移动平台上应用程序图标 flutter 插件。 https://pub.dev/packages/flutter_dynamic_icon 正文 …

zk客户端连接关闭服务端,查看znode(重补早期的学习记录)

前言:之前早期学习记录没有发布成功,丢在草稿里了,今天看到重新补一下。用作学习记录 启动zookeeper ./zkServer.sh start 连接客户端 ./zkCli.sh 后面不需参数,直接回车 回车后,这里有个watcher事件,已连接上localhost端口是默认端口2181 查看有什么命令可用 help 查…

C++类与动态内存分配

11.10 类与动态内存分配 通常&#xff0c;最好是在程序运行时(而不是编译时)确定诸如使用多少内存等问题。对于在对象中存储姓名来说&#xff0c;通常的C方法是&#xff0c;在类构造函数中使用new运算符在程序运行时分配所需的内存。为此&#xff0c;通常的方法是使用string类…

轻松解决VS配置OpenCV环境

一、OpenCV配置 1.下载OpenCV 点击进入下载OpenCV的官网界面 这里以Windows为例&#xff0c;其他同理。&#xff08;可直接下载最新&#xff09; 2.提取OpenCV 在这里浅说一句&#xff0c;为了方便环境配置文件管理&#xff0c;可以把所有关于环境配置的文件夹都放到一个叫e…

周杰伦在某手、腾格尔在某音同时开线上演唱会,八点开始谁流量高

周杰伦和腾格尔&#xff0c;都是中国华语乐坛的风云人物&#xff0c;两个人的江湖地位&#xff0c;一时之间很难分出仲伯。既然两位都是音乐界的老前辈&#xff0c;他们也准备开启历史之先河&#xff0c;两个人的线上演唱会都计划在今晚的八点开始。 虽然都是在今晚八点开启&am…