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
} }

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

  1. Servlet主要相关类核心类 容器调用的过程浅析 servlet解读 怎么调用 Servlet是什么 工作机制

      WEB简介   Web项目 是 B/S结构 浏览器/服务器模式的 浏览器发起请求,服务器作出响应   请求的发起和响应使用HTTP协议进行通讯 所谓协议也就是一种固定格式   而Socket是应用 ...

  2. html文件form表单action调用servlet连接mysql数据库实例

    web.xml文件 <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi=&qu ...

  3. JAVA-JSP内置对象之page对象调用Servlet

    相关资料:<21天学通Java Web开发> page对象1.page对象代表JSP转译后的Servlet.2.通过page对象可以非常方便地调用Servlet类中定义的方法. pageD ...

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

    需求 通用消息接口使用servlet作为服务器端服务接口,第三方应用程序通过http post的方式调用servlet,实现与通用消息接口的调用连接. 参数说明如下: msgTitle:消息标题,描述 ...

  5. JSP在页面加载时调用servlet的方法

    方法:先在JS里面写一个调用servlet的事件(可以利用ajax),然后利用<body>标签的onload调用这个事件. 代码如下: jsp文件代码如下: <%@ page lan ...

  6. web服务器调用Servlet的过程

    Servlet程序是由WEB服务器调用,web服务器收到客户端的Servlet访问请求后: Web服务器首先检查是否已经装载并创建了该Servlet的实例对象.如果是,则直接执行第④步,否则,执行第② ...

  7. 调用servlet报The requested resource is not available.

    调用servlet的时候经常有这种报错,一般来说我直到现在遇到的情况大致有以下几类: 1.参数写错了 在新创建的servlet文件中有这么一行代码,“/LoginCheck”这个一定要和form表单中 ...

  8. JQuery调用Servlet实现文件下载

    jsp页面上的txt附件,点击后浏览器默认直接打开,结果是乱码. 因为用户上传的txt文件可能是ANSI.Unicode.UTF-8编码的任意一种,上传时后台获取文件内容重写一遍保证浏览器打开正常太过 ...

  9. Apache.Tomcat 调用Servlet原理之Class类的反射机制,用orc类解释

    有一个兽人类 package com.swift.servlet; public class OrcDemo { private int hp; private int mp; private int ...

  10. struts2动态调用+Servlet过滤器+struts2拦截器

    周末真的是懒到心慌...... 本文是在完整s2sh项目基础上添加的,不太了解s2sh项目构建的朋友可以先参考一下这几篇文章: eclipse环境下基于tomcat-7.0.82构建struts2项目 ...

随机推荐

  1. SQL注入攻击和防御

    部分整理...   什么是SQL注入? 简单的例子, 对于一个购物网站,可以允许搜索,price小于某值的商品 这个值用户是可以输入的,比如,100 但是对于用户,如果输入,100' OR '1'=' ...

  2. 在Delphi中如何控制其它应用程序窗口

    在编写Delphi的应用程序中,常常涉及对其它Windows应用程序的操作.例如,在数据库的管理系统中,财务人员需要使用计算器,即可调用Windows内含的计算器功能,若每次使用,均通过“开始/程序/ ...

  3. BulletedList使用及详解

    BulletedList是一个让你轻松在页面上显示项目符号和编号格式(Bulledted List)的控件.对于ASP.NET 1.x里要动态显示Bulledted List时,要么自己利用HTML的 ...

  4. MongoDB过过瘾

    MongoDB 中默认的数据库为 test,连接后尝试以下操作 连接 插入数据:用过json的同学看到这格式相信不会陌生吧! db.person.insert({}) db.person.insert ...

  5. Chip Factory---hdu5536(异或值最大,01字典树)

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5536 题意:有一个数组a[], 包含n个数,从n个数中找到三个数使得 (a[i]+a[j])⊕a[k] ...

  6. TCP定时器

    http://network.51cto.com/art/201412/459352.htm TCP 是提供可靠的传输层,它使用的方法之一就是确认从另一端收到的数据.但是数据和确认都可能会丢失.TCP ...

  7. typedef 和 const

    1. typedef 允许你为各种数据类型定义新名字 #include <stdio.h>typedef char *ptr_to_char; //这让我看起来,好奇怪,不好读void m ...

  8. saltstack之(三)认证管理

    salt-master和salt-minion之间需要进行认证,认证之后salt-master才能管理salt-minion. 1.在node1:[root@node1 ~]# egrep -v '^ ...

  9. dd命令使用详解

    dd命令使用详解 http://www.cnblogs.com/qq78292959/archive/2012/02/23/2364760.html 1.命令简介 dd 的主要选项: 指定数字的地方若 ...

  10. mysql怎么终止当前正在执行的sql语句

    mysql怎么终止当前正在执行的sql语句 show processlist; kill 要杀的ID kill 7