HTML调用servlet(一)

摘要:
<添加html<metahttp equi=“keywords”content=“keyword1;metahttp equid=“description”content=”thiismypage“>charset=GB2312”>--<//t、 zoukankan.com/styles.css“>

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="http://t.zoukankan.com/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>
复制代码

文件整体框架如下:

HTML调用servlet(一)第7张

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="http://t.zoukankan.com/styles.css">-->

  </head>
  
  <body>
    <form name="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)+"
");
                out.print("部门名称:"+rs.getString(2)+"
");
                out.print("部门地址:"+rs.getString(3)+"
");
                out.print("部门人数:"+rs.getString(4)+"
");
            }
        } 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
    }

}
复制代码

目录结构如下:

HTML调用servlet(一)第12张

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)+"	");
                out.print("部门名称:");
                out.print(rs.getString(2)+"	");
                out.print("部门地址:");
                out.print(rs.getString(3)+"	");
                out.print("部门人数:");
                out.print(rs.getString(4)+"	");
                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
    }

}

免责声明:文章转载自《HTML调用servlet(一)》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇c# excel转换为DataTable工具CrashMonkey4IOS,Monkey测试方案 zero下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

OpenCV截取图像的某一区域

一、概述   案例:加载一张彩色图片,并截取其中的部分输出。 二、示例图片 三、示例代码 #include <opencv2/opencv.hpp> #include <iostream> using namespace cv; using namespace std; int main(int argc, char con...

并发系列(1)之 Thread 详解

本文主要结合 java.lang.Thread 源码,梳理 Java 线程的整体脉络; 一、线程概述 对于 Java 中的线程主要是依赖于系统的 API 实现的,这一点可以从 java.lang.Thread;源码中关键的方法都是 native 方法看出,也可以直接查看 OpenJDK 源码看出来,这一点后面还会讲到;对于 JDK1.8 而言,他的 Win...

Tomcat系列(6)——Tomcat处理一个HTTP请求的过程

Tomcat的架构图                图三:Tomcat Server处理一个HTTP请求的过程 处理HTTP请求过程 假设来自客户的请求为:http://localhost:8080/test/index.jsp 请求被发送到本机端口8080 1、用户点击网页内容,请求被发送到本机端口8080,被在那里监听的Coyote HTTP/1.1...

( 鲁棒性主成分分析)Robust PCA

代码:GENERALIZED PRINCIPAL COMPONENT ANALYSIS 很久很久没有写学习笔记了,现在记录一个老知识。 主成分分析,这种方法可以有效的找出数据中最“主要”的元素和结构,去除噪音和冗余,将原有的复杂数据降维,揭示隐藏在复杂数据背后的简单结构。我们知道,最简单的主成分分析方法就是PCA了。从线性代数的角度看,PCA的目标就是使用...

php 安装教程

php 安装教程  本文采用php7.0.1作为样例,进行安装。 系统环境:   CentOS6.7.   gcc 4.8.2   libzip 1.0.1 在安装之前,可以先更新CentOS系统。 yum -y update 下载相应依赖文件 wget "http://cn2.php.net/distributions/...

loki 数据库详解

介绍 LokiJS是一个面向文档的javascript数据库,与MongoDB有点相似。 它支持索引,查询和过滤数据集合。 LokiJS还支持更高级的功能,例如mapReduce,事务,并允许您实现自定义远程同步以将数据保存到服务器(或移动设备上的本地文件)。 磁盘的持久性已经在诸如nodejs之类的CommonJS环境中实现, 在移动设备上,您只需要请求...