javaweb--老杜

使用纯servlet做一个单表的CRUD操作–老杜

  • 实现步骤

    • 第一步:准备一张数据库表(sql脚本)

      • CREATE TABLE `dept` (
          `deptno` int(11) NOT NULL,
          `dname` varchar(255) DEFAULT NULL,
          `loc` varchar(255) DEFAULT NULL,
          PRIMARY KEY (`deptno`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8
        

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Gm2RN213-1688370861032)(C:\Users\26332\AppData\Roaming\Typora\typora-user-images\1.png)]

    ---
    
    • 第二步:准备一套HTML页面(项目原型)先把页面项目跑通即可,后面会做功能具体实现

      • 把HTML页面准备好

      • 然后将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="保存">
          		</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"><br>
          			部门名称<input type="text" name="dname" value="销售部"><br>
          			部门位置<input type="text" name="loc" value="北京"><br>
          			<input type="submit" value="保存">
          		</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>
          

        在这里插入图片描述

        • 欢迎页面(首页面):index.html

          <!DOCTYPE html>
          <html>
          	<head>
          		<meta charset="utf-8">
          		<title>欢迎使用OA系统</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="">删除</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="edit.html">修改</a>
          					<a href="detail.html">详情</a>
          				</td>
          			</tr>
          			<tr>
          				<td>3</td>
          				<td>30</td>
          				<td>运营部</td>
          				<td>
          					<a href="">删除</a>
          					<a href="edit.html">修改</a>
          					<a href="detail.html">详情</a>
          				</td>
          			</tr>
          		</table>
          		<hr>
          		<a href="add.html">新增部门</a>
          	</body>
          </html>
          

          在这里插入图片描述


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

      • 什么叫做一个功能?
        • 只要这个操作连接了数据库,就表示一个独立的功能
      • 包括哪些功能?
        • 查看部门列表
        • 新增部门
        • 删除部门
        • 查看部门详细信息
        • 跳转到修改页面
        • 修改部门

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

      • 创建一个webapp(给这个webapp添加servlet-api.jar和jsp-api.jar)

        • [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-6Tp7EFLf-1688370813816)(C:\Users\26332\AppData\Roaming\Typora\typora-user-images\6.png)]
      • 向webapp中添加数据库jar包(MySQL驱动)

        • 必须在WEB-INF目录下新建lib目录,然后将MySQL的驱动jar包拷贝到这个lib目录下,这个必须叫lib。
        • [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-sq1keVDP-1688370813817)(C:\Users\26332\AppData\Roaming\Typora\typora-user-images\7.png)]
        • [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-7lhGjMxq-1688370813817)(C:\Users\26332\AppData\Roaming\Typora\typora-user-images\8.png)]
      • JDBC的工具类

        • [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-XM9ynL2H-1688370813817)(C:\Users\26332\AppData\Roaming\Typora\typora-user-images\9.png)]

        • //配置文件信息
          driver=con.musql.jdbc.Driver
          url=jdbc:mysql://localhost:3306/javaweb
          user=root
          password=123456
          
        • package ServletProject.utils;
          
          import java.beans.Statement;
          import java.sql.Connection;
          import java.sql.DriverManager;
          import java.sql.ResultSet;
          import java.sql.SQLException;
          import java.util.ResourceBundle;
          
          /*
          * JDBC的工具类
          * */
          public class DButil {
                     
          
              //静态变量,在类加载时执行
              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 {
                     
                  //注册驱动,执行一次即可,放在静态代码块当中,类加载时执行
                  try{
                     
                      //"com.mysql.jdbc.Driver"是链接数据库的驱动,不能写死,因为以后可能会链接Oracle数据库,以防修改Java源代码,保证项目正常。
                      Class.forName(driver);
                  }catch (ClassNotFoundException e){
                     
                      e.printStackTrace();
                  }
          
              }
              //获取数据库链接对象
              public static Connection getConnection() throws SQLException {
                     
                  //获取链接
                  Connection conn= DriverManager.getConnection(url,user,password);
                  return conn;
              }
          
              //释放资源
              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();
                      }
                  }
              }
          }
          
          

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

      • 第一:先修改前端欢迎页面的超链接,因为用户先点击的就是这个超链接

        • <!-- 前端超链接发送请求的时候,请求路径以/开始,并且要带着项目名-->
          		<a href="/ServletProject/dept/list">查看部门列表</a>
          
      • 第二:编写web.xm文件

            <servlet>
                <servlet-name>list</servlet-name>
                <servlet-class>????</servlet-class>
            </servlet>
            <servlet-mapping>
                <servlet-name>list</servlet-name>
                <url-pattern>/dept/list</url-pattern>
            </servlet-mapping>
        
      • 第三:编写DeptListServlet类继承HttpServlet类,然后重写doGet方法

        • package action;
          
          import jakarta.servlet.ServletException;
          import jakarta.servlet.http.HttpServlet;
          import jakarta.servlet.http.HttpServletRequest;
          import jakarta.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方法中链接数据库,查询所有的部门,动态展示部门列表页面

        • 分析list.html页面那部分是固定死的,那部分是变化的

        • package action;
          //查看部门列表功能实现
          import ServletProject.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;
          
          public class DeptListServlet 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 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,dname,loc from dept";
                      ps=conn.prepareStatement(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='edit.html'>修改</a>");
                          out.print("					<a href='detail.html'>详情</a>");
                          out.print("				</td>");
                          out.print("			</tr>");
                      }
                  } catch (SQLException throwables) {
                     
                      throwables.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>");
              }
          }
          
          
        • 现在写完这个功能之后,你会有一种感觉,感觉开发很繁琐,只写servlet代码太麻烦了


    • 第六步:实现查看部门详情功能(从前端往后端一步一步实现)

      • 首先要考虑的是,用户点击的是什么?用户点击的东西在哪里?

        • 一定要先找到用户点的“详情”在哪里,在Java程序中找到了

        • <a href='/ServletProject/dept/detail'>详情</a>
          
        • 详情这里是需要连接数据库的,所以这个超链接点击之后也是需要执行一段Java代码的,所以这里的超链接路径是servlet对象

        • 注意:修改路径之后,这个路径是需要加项目名的(前端向后端发送请求需要加项目名)

        • 又因为根路径可以动态获取,所以这里可以更改为:

          //获取应用的根路径
          String contextPath = request.getContextPath();
          <a href='"+contextPath+"/dept/detail'>详情</a>
          
        • 又又因为详情需要有判断具体是那个部门的详情,所以在发送请求的时候可以把部门编号发送给后端,后端通过数据库来选出相应的部门信息:

          <a href='"+contextPath+"/dept/detail?"+deptno+"'>详情</a>
          
        • 接下来就需要完成该功能的servlet对象就行了:

          • 编写一个DeptDetailServlet继承HttpServlet,重写doGet方法,在该方法中连接数据库,查询相应部门信息

          • package action;
            
            import ServletProject.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;
            
            public class DeptDetailServlet extends HttpServlet {
                         
                @Override
                protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                         
                    //获取请求中url的部门编号
                    String deptno=request.getParameter("deptno"
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值