html调用servlet(JDBC在Servlet中的使用)(2)

5.修改数据

5.1编写查询条件页面

修改单条数据的时候,首先是查询出单个数据的详细信息,然后根据实际需要部分修改或者全部修改。修改之后,数据会提交到数据库,数据库中保存更新以后的数据。

查询出单条数据的查询条件页面代码如下:

QueryToUpdate.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>QueryToUpdate.html</title>

    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="this is my page">
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">

    <!--<link rel="stylesheet" type="text/css" href="./styles.css">-->

  </head>

  <body>
    <form name="f1" id="f1" action="/jdbc_servlet/servlet/QueryToUpdateServlet" method="post">
      <table border="0">
        <tr>
          <td>请输入要修改的部门编号:</td><tr></tr>
          <td><input type="text" name="id" ></td>
        </tr>
        <tr>
          <td colspan="2" align="left"><input type="submit" value="提交"></td>
        </tr>
      </table>
    </form>
  </body>
</html>

5.2 编写显示部门详细信息的Servlet

输入要修改的部门编号以后,进入根据部门编号查询部门信息的Servlet,把部门详细信息显示到页面中,一些不可以修改的字段可以设置成只读,这样就不会把这些数据修改了,该Servlet的代码如下:

QueryToUpdateServlet.java

package com.cn.update;

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

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

public class QueryToUpdateServlet extends HttpServlet {

    /**
     * Destruction of the servlet. <br>
     */
    public void destroy() {
        super.destroy(); // Just puts "destroy" string in log
        // Put your code here
    }

    /**
     * The doGet method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to get.
     *
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html;charset=gb2312");
        request.setCharacterEncoding("gb2312");
        PrintWriter out = response.getWriter();
        String id = request.getParameter("id");
        Connection con = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            System.out.println("创建驱动成功!");
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/bank", "root", "1234");
            System.out.println("数据库连接成功!");
            String sql = "SELECT * FROM dept WHERE id=?";
            pstmt = con.prepareStatement(sql);
            pstmt.setString(1, id);
            rs = pstmt.executeQuery();
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //显示单个部门的信息
        out.println("<html>"
                + "<head><title>显示单个部门信息</title></head>"
                + "<body>");
        out.println("<h1>显示单个部门信息</h1><br><br>");
        out.print("<form action=‘/jdbc_servlet/servlet/UpdateDeptServlet‘ method=‘post‘>");
        try {
            while(rs.next()){
                out.println("部门编号:");
                out.print("<br>");
                //在文本框中显示部门编号,设置成只读
                out.println("<input type=‘text‘ name=‘id‘ readonly=‘true‘ value=");
                out.println(rs.getString(1).toString());
                out.print(">");
                out.print("<br>");
                out.println("部门名称:");
                out.print("<br>");
                //在文本框中显示部门名称
                out.println("<input type=‘text‘ name=‘d_name‘ value=");
                out.println(rs.getString(2).toString());
                out.print(">");
                out.print("<br>");
                out.println("部门地址:");
                out.print("<br>");
                //在文本框中显示部门地址
                out.println("<input type=‘text‘ name=‘address‘ value=");
                out.println(rs.getString(3).toString());
                out.print(">");
                out.print("<br>");
                out.println("部门人数:");
                out.print("<br>");
                //在文本框中显示部门人数
                out.println("<input type=‘text‘ name=‘empnumber‘ value=");
                out.println(rs.getString(4).toString());
                out.print(">");
                out.print("<br>");
                //提交按钮
                out.print("<input type=‘submit‘ value=‘Submit‘>");
                out.print("</form>");

            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        out.flush();
        out.close();
    }

    /**
     * The doPost method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to post.
     *
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html;charset=gb2312");
        request.setCharacterEncoding("gb2312");
        PrintWriter out = response.getWriter();
        this.doGet(request, response);
        out.flush();
        out.close();
    }

    /**
     * Initialization of the servlet. <br>
     *
     * @throws ServletException if an error occurs
     */
    public void init() throws ServletException {
        // Put your code here
    }

}

5.3编写处理修改操作的Servlet

在UpdateDeptServlet中,修改数据以后,显示出数据库表中的全部信息。UpdateDeptServlet的代码如下:

UpdateDeptServlet.java

package com.cn.update;

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

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

public class UpdateDeptServlet extends HttpServlet {

    /**
     * The doGet method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to get.
     *
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        this.doPost(request, response);
        out.flush();
        out.close();
    }

    /**
     * The doPost method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to post.
     *
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html;charset=gb2312");
        request.setCharacterEncoding("gb2312");
        PrintWriter out = response.getWriter();
        Connection con = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        Statement sta = null;
        String id = request.getParameter("id");
        String address = request.getParameter("address");
        int empnumber = Integer.parseInt(request.getParameter("empnumber"));
        String d_name = request.getParameter("d_name");
        try {
            Class.forName("com.mysql.jdbc.Driver");
            System.out.println("创建驱动成功!");
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/bank", "root", "1234");
            System.out.println("数据库连接成功!");
            String sql = "UPDATE dept SET id=?,address=?,empnumber=?,d_name=? WHERE id=?";
            ps = con.prepareStatement(sql);
            //下面设置修改的数据值
            ps.setString(1, id);
            ps.setString(2, address);
            ps.setInt(3, empnumber);
            ps.setString(4, d_name);
            ps.setString(5, id);
            ps.executeUpdate();
            System.out.println("修改成功!");
            /*
             * 添加成功后,显示全部信息
             */
            sta = con.createStatement();
            rs = sta.executeQuery("SELECT * FROM dept");
            //在页面中显示表中的所有信息
            out.println(
                    "<html>"+
                    "<head><title>部门表信息</title></head>"+
                    "<body>");
            out.println("<h1>部门表信息:</h1><br><br>");
            //循环遍历输出查询结果
            while(rs.next()){
                out.print("部门编号:");
                out.print(rs.getString(1)+"\t");
                out.print("部门名称:");
                out.print(rs.getString(2)+"\t");
                out.print("部门地址:");
                out.print(rs.getString(3)+"\t");
                out.print("部门人数:");
                out.print(rs.getString(4)+"\t");
                out.println("<br>");
            }
            out.print("</body></html>");
            out.close();
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        out.flush();
        out.close();
    }

    /**
     * Initialization of the servlet. <br>
     *
     * @throws ServletException if an error occurs
     */
    public void init() throws ServletException {
        // Put your code here
    }

}

6. 删除数据

删除数据时,要指定删除的条件,否则会把表中的所有数据删除。删除以后,被删除的数据在表中就不存在了。下面的例子是根据部门编号删除数据的例子。首先在页面中输入要删除的部门编号,输入要删除的部门编号的页面代码入下:

delete.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>delete.html</title>

    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="this is my page">
    <meta http-equiv="content-type" content="text/html; charset=gb2312">

    <!--<link rel="stylesheet" type="text/css" href="./styles.css">-->

  </head>

  <body>
    <form name="f1" id="f1" action="/jdbc_servlet/servlet/DeleteByIdServlet" method="post">
      <table border="0">
        <tr>
          <td>请输入要删除的部门编号:</td><tr></tr>
          <td><input type="text" name="id" ></td>
        </tr>
        <tr>
          <td colspan="2" align="left"><input type="submit" value="删除"></td>
        </tr>
      </table>
    </form>
  </body>
</html>

当输入删除条件后,单击【删除】按钮,会进入form表单指定的DeleteByIdServlet中,这是一个servlet,用来处理删除操作。DeleteByIdServlet中的代码如下:

DeleteByIdServlet.java

package com.cn.delete;

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

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

public class DeleteByIdServlet extends HttpServlet {

    /**
     * The doGet method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to get.
     *
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        this.doPost(request, response);
        out.flush();
        out.close();
    }

    /**
     * The doPost method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to post.
     *
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html;charset=gb2312");
        request.setCharacterEncoding("gb2312");
        PrintWriter out = response.getWriter();
        String id = request.getParameter("id");
        Connection con = null;
//        ResultSet rs = null;
        PreparedStatement ps = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            System.out.println("创建驱动成功!");
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/bank", "root", "1234");
            System.out.println("数据库连接成功!");
            String sql = "DELETE FROM dept WHERE id=?";
            ps = con.prepareStatement(sql);
            ps.setString(1, id);
            ps.executeUpdate();
            System.out.println("删除成功!");
            //显示结果信息
            out.println("<html><head><title>"
                    +"删除部门表数据</title></head>"+"<body>");
            out.println("<h1>删除部门表数据成功!</h1>");
            out.print("</body></html>");
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        out.flush();
        out.close();
    }

    /**
     * Initialization of the servlet. <br>
     *
     * @throws ServletException if an error occurs
     */
    public void init() throws ServletException {
        // Put your code here
    }

}

在DeleteByIdServlet中,获得页面传递过来的部门编号,然后根据部门编号删除该编号对应的数据,删除成功则在页面中提示删除成功。

时间: 2024-10-29 04:04:15

html调用servlet(JDBC在Servlet中的使用)(2)的相关文章

使用servlet+jdbc+MD5实现用户加密登录

/** * 分析流程: * 1.前端页面提交登录请求 * 2.被web.xml拦截,进入到LoginServlet(有两种方式:方式一,在web.xml文件中配置servlet拦截器;方式二,不用在web.xml中配置,直接在类中通过                   @WebServlet("/login")注解    //请求路径) * 3.获取页面输入的用户名和密码 * 4.创建一个工具类,用于生成连接工厂 * 5.调用UserDao层,通过连接工厂连接数据库,根据名字查询用户

使用JSP+Servlet+Jdbc+Echatrs实现对豆瓣电影Top250的展示

使用JSP+Servlet+Jdbc+Echatrs实现对豆瓣电影Top250的展示 写在前面: 有的小伙伴,会吐槽啦,你这个标题有点长的啊.哈哈 ,好像是的!不过,这个也是本次案例中使用到的关键技术.如果,你正愁不会的数据可视化,那么我接下来,我会带你一步一步的实现这个数据可视化的功能. 效果图: 开发工具:我们选择的是IDEA,你还得准备一个豆瓣top250的数据源,我这里用python爬虫抓取统计了豆瓣top250电影各个国家电影数量.如何你担心,没有数据.先不用担心,我会提供的. 小建议

在Java代码(非JSP及Action,Servlet,Controller)中获得WebRoot的物理路径

在开发Web方面的应用时, 经常需要获取 服务器中当前WebRoot的物理路径; 如果是Servlet , Action , Controller, 或则Filter , Listener , 拦截器等相关类时, 我们只需要获得ServletContext, 然后通过ServletContext.getRealPath("/")来获取当前应用在服务器上的物理地址. 如果在类中取不到ServletContext时, 有两种方式可以做到 1) 利用Java的类加载机制 调用 XXX.cla

基于Servlet+JDBC+Bootstrap+MySQL+AJAX权限管理系统项目实战教程

项目简介 权限系统一直以来是我们应用系统不可缺少的一个部分,若每个应用系统都重新对系统的权限进行设计,以满足不同系统用户的需求,将会浪费我们不少宝贵时间,所以花时间来设计一个相对通用的权限系统是很有意义的.     本系统的设计目标是对应用系统的所有资源进行权限控制,比如应用系统的功能菜单.各个界面等进行权限的操控.技术介绍 · Servlet3.0 Servlet 3.0 作为JavaEE6 规范体系中一员,随着JavaEE6规范一起发布.该版本在前一版本(Servlet2.5)的基础上提供了

【Listener】利用监听器Listener以MVC的思想通过JSP+Servlet+JDBC完成在线用户列表的输出

Servlet,监听器Listener与<[Filter]拦截器Filter>(点击打开链接)是JSP的三大核心组件,实际上监听器Listener相当于数据库里面的触发器,一旦用户触发了某种行为,则可以通过相关的Java文件执行相应的程序.用户在浏览网页的过程中,主要有打开浏览器的动作,对应的行为是Session的创建,可是,用户关闭浏览器的动作,并不是对应Session的消失,因此对于Session的消失我们意义不大:访问任意网页的动作,对应的行为是request请求的创建,request的

jsp+servlet+jdbc实现对数据库的增删改查

一.JSP和Servlet的简单介绍 1.Servlet和JSP简介: Java开发Web应用程序时用到的技术主要有两种,即Servlet和JSP,Servlet是在服务器端执行的Java程序,一个被称为Servlet容器的程序(其实就是服务器) 负责执行Java程序,而JSP(Java Server Page)则是一个页面, 由JSP容器负责执行. 2.Servlet和JSP的区别: Servlet以Java程序为主, 输出HTML代码时需要使用out.println函数,也就是说Java中内

简单使用JDBC和Servlet实现用户注册和登录功能

简单的浏览了一下Servlet和JDBC方面的知识,于是写了一下简单使用JDBC和Servlet实现用户注册和登录功能,具体实现如下: 一.大体的编码思路 1.1.注册功能 获取注册页面提交的username.password和repeatPassword: 判断password和 repeatPassword是否一致,一致就继续执行程序,不一致则结束程序: 遍历数据库中tb_user,查看数据库中是否存在username,存在则结束程序,不存在则继续进行程序,实现注册功能: 1.2.登录功能

javabean+jsp+servlet+jdbc从软件安装到开发实例

javabean\jsp\servlet\jdbc的作用: JavaBean:用于传递数据,拥有与数据相关的逻辑处理.JSP:从Model接收数据并生成HTML.Servlet:接收HTTP请求并控制Model和View.jdbc:用于配置环境 首先新建course的数据库:包含name,teacher,classroom,id等字段. 源代码及包的分布 package com.hjf.dao; import java.sql.Connection; import java.sql.Result

传统的Servlet在spring boot中怎么实现的?

本文主要内容: 1:springboot一些介绍 2:传统的servlete项目在spring boot项目中怎么实现的?web.xml.url-patterns怎么设置? 3:有几种实现方式?分别是什么? 4:代码位置 spring boot 三大特性 组件自动装配:webMVC.webFlux.JDBC等 嵌入式Web容器:Tomcat.Jetty以及undertow 生产准备特性:指标.健康检查.外部化部署等 组件自动装配: 激活自动装配注解:@EnableAutoConfiguratio

JSP+Servlet+JDBC+Mysql实现的博客系统

本文存在视频版本,请知悉 项目简介 项目来源于:https://gitee.com/nanpingping/jsp-blog 这次分享个人博客系统,界面简洁大气,功能齐全,是不可多得的比较容易的系统,非常适合毕业设计或者课程设计. 本系统基于JSP+Servlet+JDBC+Mysql.涉及技术少,易于理解,适合JavaWeb初学者学习使用. 难度等级:简单 技术栈 编辑器 IntelliJ IDEA 2019.1.1 (Ultimate Edition) 前端技术 基础:html+css+Ja