html调用servlet(JDBC在Servlet中的使用)(1)
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(JDBC在Servlet中的使用)(1)的更多相关文章
- Java Servlet(三):Servlet中ServletConfig对象和ServletContext对象
本文将记录ServletConfig/ServletContext中提供了哪些方法,及方法的用法. ServletConfig是一个抽象接口,它是由Servlet容器使用,在一个servlet对象初始 ...
- 登录小项目 js+servlet+jdbc+mvc
项目名称: 沪上阿姨 实现需求: 实现用户登录 实现用户退出 实现用户注册 功能分析: 用户登录: 根据用户名和密码查询用户信息.查询则登录成功,查不到则登录失败. 用户退出: 销毁session 用 ...
- JDBC和servlet设计思路、DAO模式思路、MVC思路粗略总结
#JDBC和Servlet联合起来使用的项目思路: 说明:建库,最好一开始设置utf8字符集 step1: 在数据库中建表 如 create table t_user{ ...... } step ...
- Jsp+Servlet+JDBC的使用复习
最近对JDBC进行了复习,对事物的理解,连接池的使用等部分都有一个复习,所以使用Servlet+JDBC完成了一个小Demo,在这里对这种底层的操作进行总结.框架的使用的确方便了我们的开发,但是底层的 ...
- java web开发基础实例(javabean+jsp+servlet+jdbc)
JavaBean:用于传递数据,拥有与数据相关的逻辑处理 JSP:从Model接收数据并生成HTML Servlet:接收HTTP请求并控制Model和View jdbc:用于配置环境 一.[建立数据 ...
- 使用JSP+Servlet+Jdbc+Echatrs实现对豆瓣电影Top250的展示
使用JSP+Servlet+Jdbc+Echatrs实现对豆瓣电影Top250的展示 写在前面: 有的小伙伴,会吐槽啦,你这个标题有点长的啊.哈哈 ,好像是的!不过,这个也是本次案例中使用到的关键技术 ...
- 使用servlet+jdbc+MD5实现用户加密登录
/** * 分析流程: * 1.前端页面提交登录请求 * 2.被web.xml拦截,进入到LoginServlet(有两种方式:方式一,在web.xml文件中配置servlet拦截器;方式二,不用在w ...
- Servlet从本地文件中读取图片,并显示在页面中
import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpSer ...
- MVC-1(javabean+jsp+servlet+jdbc)
这是一篇最初版本的mvc设计模式的demo.路要一步一步走,弄明白这其中的逻辑,对后面掌握ssh,ssm等框架大有裨益. 计算机系的同学们也要为毕设做准备了,希望可以帮你们迈出自己做毕设的第一步(微笑 ...
随机推荐
- Loadrunner上传文件解决办法(大文件)
Loadrunner上传文件解决办法(大文件) 最近再做一个跟海量存储相关的项目测试,需要通过LR模拟用户大量上传和下载文件,请求是Rest或Soap,同时还要模拟多种大小尺寸不一的文件 通常情况下, ...
- SPOJ - SUBLEX 后缀自动机
SPOJ - SUBLEX 思路:求第k大字串,求出sam上每个节点开始能识别多少字串,然后从起点开始跑就好啦. #include<bits/stdc++.h> #define LL lo ...
- ubuntu12.04上的mongodb卸载
如果您需要卸载 mongodb,然后有几种方法来完成这取决于你想实现. 一.卸载只是 mongodb 这将删除只是 mongodb 包本身. 1 sudo apt-get remove mongodb ...
- 2018年全国多校算法寒假训练营练习比赛(第二场)F - 德玛西亚万岁
链接:https://www.nowcoder.com/acm/contest/74/F来源:牛客网 题目描述 德玛西亚是一个实力雄厚.奉公守法的国家,有着功勋卓著的光荣军史. 这里非常重视正义.荣耀 ...
- CSUOJ 1007 矩形着色
Description Danni想为屏幕上的一个矩形着色,但是她想到了一个问题.当点击鼠标以后电脑是如何判断填充的区域呢? 现在给你一个平面直角坐标系,其中有一个矩形和一个点,矩形的四条边均是平行于 ...
- 海康威视 - 萤石云开放平台 js 版
开放平台 https://open.ys7.com/mobile/download.html API http://open.ys7.com/doc/zh/uikit/uikit_javascript ...
- BOM知识梳理
学过前端开发的地球人应该都了解,JavaScript分为三个部分:ECMAScript(JS语言本身基础语法),DOM(文档对象模型,应用程序编程接口),BOM(浏览器对象模型). BOM,实际上与浏 ...
- Java实现杨辉三角形
Java实现杨辉三角形 一.源代码:YFTriangle.java package cn.com.zfc.day009; import java.util.Scanner; /** * 打印杨辉三角形 ...
- Java 的类加载顺序
Java 的类加载顺序 一.加载顺序:先父类后子类,先静态后普通 1.父类的静态成员变量初始化 2.父类的静态代码块 3.子类的静态成员变量初始化 4.子类的静态代码块 5.父类的普通成员变量初始化 ...
- [BZOJ3638 && BZOJ3272]带修区间不相交最大K子段和(线段树模拟费用流)
https://www.cnblogs.com/DaD3zZ-Beyonder/p/5634149.html k可重区间集问题有两种建图方式,可能这一种才可以被线段树优化. 换个角度看,这也是一个类似 ...