HTML调用servlet(一)

1.页面的数据表单

在使用Servlet处理用户请求之前,先准备一个页面,该页面用来提供数据表单。数据表单就是HTML中的<form>...</form>部分,当用户单击Submit按钮提交表单之后,表单中包含的一些变量(或者成为字段)将会被发送到服务器端进行处理。下面编写一个HTML文件,文件代码如下:

add.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>add.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 action="/jdbc_servlet/servlet/addServlet" method="post">
      <label>请输入部门信息:</label><br><br>
      <label>部门号:</label><br>
      <input type="text" name="id"/><br>
      <label>部门名:</label><br>
      <input type="text" name="name"/><br>
      <label>部门人数:</label><br>
      <input type="text" name="num"/><br>
      <label>地址:</label><br>
      <input type="text" name="address"/><br><br>
      <input type="submit" value="提交"/><br>
    </form>
  </body>
</html>

2.添加数据

Servlet的好处之一就是可以简单地获得表单中的数据。在Servlet中使用JDBC技术实现添加的代码如下:

addServlet.java

package com.cn.add;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
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 addServlet extends HttpServlet {

    /**
     * Constructor of the object.
     */
    public addServlet() {
        super();
    }

    /**
     * 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");
        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 {
        System.out.println("到了Servlet!!!");
        response.setContentType("text/html;charset=gb2312");
        request.setCharacterEncoding("gb2312");
        PrintWriter out = response.getWriter();
        String id = request.getParameter("id");   //获取部门编号
        String name = request.getParameter("name");    //获取部门名称
        String address = request.getParameter("address"); //获取部门所在地址
        int num = Integer.parseInt(request.getParameter("num")); //获取部门人数
        Connection conn = null; //声明一个Connection对象,用来连接数据库
        PreparedStatement pstmt = null; //声明PreparedStatement对象,用来向数据库插入数据条数据
        try {
            //连接到MySQL数据库中的bank数据库模式
            Class.forName("com.mysql.jdbc.Driver");
            System.out.println("创建驱动成功!");
            //连接数据库
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/bank", "root", "1234");
            System.out.println("连接数据库成功!");
            //插入数据的SQL语句
            String sql = "INSERT INTO dept(id,d_name,address,empnumber) VALUES(?,?,?,?)";
            pstmt = conn.prepareStatement(sql);
            //设置插入数据的顺序
            pstmt.setString(1, id);
            pstmt.setString(2, name);
            pstmt.setString(3, address);
            pstmt.setInt(4, num);
            int result = pstmt.executeUpdate();
            //判断执行结果
            if (result == 1) {
                out.print("插入数据成功!");
            }else {
                out.print("插入数据失败!请重新插入!");
            }
        } 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
    }

}

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>addServlet</servlet-name>
    <servlet-class>com.cn.add.addServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>addServlet</servlet-name>
    <url-pattern>/servlet/addServlet</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

文件整体框架如下:

3.查看单条数据

一般一条数据的id是唯一的,查看单条记录的时候,可以根据id来查询。HTML页面的代码如下:

showById.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>showById.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/SearchEmployee" 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>

在该页面中输如id号,点击查找按钮时会进入查询的Servlet,在Servlet中处理根据id查询的操作。根据id查询的Servlet代码如下:

SearchEmployee.java

package com.cn.query;

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 SearchEmployee 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 conn = null;  //声明一个Connection对象,用来连接数据库
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            System.out.println("创建驱动成功!");
            //连接数据库
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/bank", "root", "1234");
            System.out.println("连接数据库成功!");
            String sql = "SELECT * FROM dept WHERE id = ?";
            pstmt = conn.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();
        }
        try {
            while(rs.next()){
                out.print("部门编号:"+rs.getString(1)+"\n");
                out.print("部门名称:"+rs.getString(2)+"\n");
                out.print("部门地址:"+rs.getString(3)+"\n");
                out.print("部门人数:"+rs.getString(4)+"\n");
            }
        } 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
    }

}

目录结构如下:

4.显示一张表中的全部数据

显示表中全部数据信息的Servlet代码如下:

DeptList.java

package com.cn.query;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
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 DeptList 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;charset=gb2312");
        request.setCharacterEncoding("gb2312");
        PrintWriter out = response.getWriter();
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/bank", "root", "1234");
            stmt = conn.createStatement();
            rs = stmt.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.print("<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();
        }
    }

    public void init() throws ServletException {
        // Put your code here
    }

}
时间: 2024-10-14 00:45:26

HTML调用servlet(一)的相关文章

java类中调用servlet

一.Java中调用servlet说明: 我们有时可能需要在Java类中调用Servlet从而实现某些特殊的功能,在JavaAPI中提供了一个URL的类,其中openStream( )方法可以打开URL的连接,并返回一个用于该连接读入的InputStream. 二.Java中调用servlet应用举例: package com.solid.test; import java.io.BufferedReader; import java.io.IOException; import java.io.

C#调用Servlet

需求 通用消息接口使用servlet作为服务器端服务接口,第三方应用程序通过http post的方式调用servlet,实现与通用消息接口的调用连接. 参数说明如下: msgTitle:消息标题,描述发送消息的标题 serviceId:服务编号,消息的服务编号 msgDesp:消息描述,消息的详细内容 msgURL:URL地址,消息中包含的 URL 上述4个参数的参数值可以为空,但参数必须提供. 调用示例 下面一段简单的html代码,描述了如何通过网页进行调用通用消息接口的模式,供参考. <ht

[C#/Java] C#中调用Servlet示例

需求 通用消息接口使用servlet作为服务器端服务接口,第三方应用程序通过http post的方式调用servlet,实现与通用消息接口的调用连接. 参数说明如下: msgTitle:消息标题,描述发送消息的标题 serviceId:服务编号,消息的服务编号 msgDesp:消息描述,消息的详细内容 msgURL:URL地址,消息中包含的 URL 上述4个参数的参数值可以为空,但参数必须提供. 调用示例 下面一段简单的html代码,描述了如何通过网页进行调用通用消息接口的模式,供参考. <ht

HTML调用servlet(二)

5.修改数据 5.1编写查询条件页面 修改单条数据的时候,首先是查询出单个数据的详细信息,然后根据实际需要部分修改或者全部修改.修改之后,数据会提交到数据库,数据库中保存更新以后的数据. 查询出单条数据的查询条件页面代码如下: QueryToUpdate.html <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>Que

HTML中调用servlet的问题(?)

最近在学习servlet.刚开始时,按照案例一行一行的敲代码.不过,出问题了. hello1.html 1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="UTF-8"> 5 </head> 6 <body style="font-size:24px"> 7 <form action="hello1" method=

struts中调用servlet的两种方法——IcC方式和非IoC方式的代码demo

1 package com.java1234.action;//所在的包 2 3 import java.sql.Connection;//数据库连接的类 4 import java.util.ArrayList;//ArrayList和List是在private List<DataDic> dataDicList=new 5 6 ArrayList<DataDic>();中用到 7 import java.util.List;//ArrayList和List是在private L

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

5.修改数据 5.1编写查询条件页面 修改单条数据的时候,首先是查询出单个数据的详细信息,然后根据实际需要部分修改或者全部修改.修改之后,数据会提交到数据库,数据库中保存更新以后的数据. 查询出单条数据的查询条件页面代码如下: QueryToUpdate.html <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>Que

Servlet的调用过程_生命周期_继承结构

Servlet调用过程 浏览器上输入网站,dns解析域名成服务器的IP地址,浏览器带着一个请求行,和众多request请求头,找服务器. 1.分析请求的是哪台虚拟主机,查看Host请求头,如果没有Host请求头就访问缺省虚拟主机 2.分析访问的是当前虚拟主机中的哪个web资源,从请求行中分析出当前访问哪个web应用的资源 3.查找web.xml,查看有没有对应的虚拟路径 Servlet的生命周期 1.Servlet在第一次被访问到的时候,服务器创建出Servlet对象. 2.创建出对象之后,立即

《Servlet学习笔记》Servlet生命周期和调用

    学习技术有时会感觉很枯燥,有时感觉很绕,N多调用,不好理解,但如果能画出图来,就可以一目了然. 图比文字更容易让人接受,并产生深刻印象.一张图可以包含很多东西. 下面一些图来自于网络,偶然间发现,感觉让人忽然明白并回忆起了好多. Servlet程序是由WEB服务器调用,web服务器收到客户端的Servlet访问请求后: Web服务器首先检查是否已经装载并创建了该Servlet的实例对象.如果是,则直接执行第四步,否则,执行第二步: 装载并创建该Servlet的一个实例对象: 调用Serv