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

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

1.页面的数据表单

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

add.html

add.html-->请输入部门信息:

部门号:

部门名:

部门人数:

地址:



2.添加数据

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

addServlet.java

packagecom.cn.add;importjava.io.IOException;importjava.io.PrintWriter;importjava.sql.Connection;importjava.sql.DriverManager;importjava.sql.PreparedStatement;importjava.sql.SQLException;importjavax.servlet.ServletException;importjavax.servlet.http.HttpServlet;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;publicclassaddServletextendsHttpServlet {/*** Constructor of the object.*/publicaddServlet() {super();

}/*** Destruction of the servlet.
*/publicvoiddestroy() {super.destroy();//Just puts "destroy" string in log//Put your code here}/*** The doGet method of the servlet.

*

* This method is called when a form has its tag value method equals to get.

*

*@paramrequest the request send by the client to the server

*@paramresponse the response send by the server to the client

*@throwsServletException if an error occurred

*@throwsIOException if an error occurred*/publicvoiddoGet(HttpServletRequest request, HttpServletResponse response)throwsServletException, 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.

*

* This method is called when a form has its tag value method equals to post.

*

*@paramrequest the request send by the client to the server

*@paramresponse the response send by the server to the client

*@throwsServletException if an error occurred

*@throwsIOException if an error occurred*/publicvoiddoPost(HttpServletRequest request, HttpServletResponse response)throwsServletException, 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");//获取部门所在地址intnum = 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);intresult =pstmt.executeUpdate();//判断执行结果if(result == 1) {

out.print("插入数据成功!");

}else{

out.print("插入数据失败!请重新插入!");

}

}catch(ClassNotFoundException e) {//TODO Auto-generated catch blocke.printStackTrace();

}catch(SQLException e) {//TODO Auto-generated catch blocke.printStackTrace();

}

out.flush();

out.close();

}/*** Initialization of the servlet.

*

*@throwsServletException if an error occurs*/publicvoidinit()throwsServletException {//Put your code here}

}

web.xml


http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">This is the description of my J2EE componentThis is the display name of my J2EE componentaddServletcom.cn.add.addServletaddServlet/servlet/addServletindex.jsp

文件整体框架如下:

3.查看单条数据

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

showById.html

showById.html-->请输入部门编号:

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

SearchEmployee.java

packagecom.cn.query;importjava.io.IOException;importjava.io.PrintWriter;importjava.sql.Connection;importjava.sql.DriverManager;importjava.sql.PreparedStatement;importjava.sql.ResultSet;importjava.sql.SQLException;importjavax.servlet.ServletException;importjavax.servlet.http.HttpServlet;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;publicclassSearchEmployeeextendsHttpServlet {/*** Destruction of the servlet.
*/publicvoiddestroy() {super.destroy();//Just puts "destroy" string in log//Put your code here}/*** The doGet method of the servlet.

*

* This method is called when a form has its tag value method equals to get.

*

*@paramrequest the request send by the client to the server

*@paramresponse the response send by the server to the client

*@throwsServletException if an error occurred

*@throwsIOException if an error occurred*/publicvoiddoGet(HttpServletRequest request, HttpServletResponse response)throwsServletException, 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 blocke.printStackTrace();

}catch(SQLException e) {//TODO Auto-generated catch blocke.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 blocke.printStackTrace();

}

out.flush();

out.close();

}/*** The doPost method of the servlet.

*

* This method is called when a form has its tag value method equals to post.

*

*@paramrequest the request send by the client to the server

*@paramresponse the response send by the server to the client

*@throwsServletException if an error occurred

*@throwsIOException if an error occurred*/publicvoiddoPost(HttpServletRequest request, HttpServletResponse response)throwsServletException, 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.

*

*@throwsServletException if an error occurs*/publicvoidinit()throwsServletException {//Put your code here}

}

目录结构如下:

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

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

DeptList.java

packagecom.cn.query;importjava.io.IOException;importjava.io.PrintWriter;importjava.sql.Connection;importjava.sql.DriverManager;importjava.sql.ResultSet;importjava.sql.SQLException;importjava.sql.Statement;importjavax.servlet.ServletException;importjavax.servlet.http.HttpServlet;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;publicclassDeptListextendsHttpServlet {/*** The doGet method of the servlet.

*

* This method is called when a form has its tag value method equals to get.

*

*@paramrequest the request send by the client to the server

*@paramresponse the response send by the server to the client

*@throwsServletException if an error occurred

*@throwsIOException if an error occurred*/publicvoiddoGet(HttpServletRequest request, HttpServletResponse response)throwsServletException, 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(""+                    "部门表信息"+                    "");

out.println("

部门表信息:



");//循环遍历输出查询结果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("
");

}

out.print("");

out.close();

}catch(ClassNotFoundException e) {//TODO Auto-generated catch blocke.printStackTrace();

}catch(SQLException e) {//TODO Auto-generated catch blocke.printStackTrace();

}

}publicvoidinit()throwsServletException {//Put your code here}

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,740评论 18 399
  • 这部分主要是与Java Web和Web Service相关的面试题。 96、阐述Servlet和CGI的区别? 答...
    杂货铺老板阅读 1,425评论 0 10
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,841评论 18 139
  • 作者:樊荣强 我发现,初入社会,初入职场的许多年轻人,常常为人际关系而感到困惑。而这些困惑当中,最突出的一个就是,...
    樊荣强阅读 14,332评论 96 650
  • 开启我的iOS路 我在大学所学的专业是.net,但是其实在大二时候我对编程基本上还处于一无所知的状态。我也...
    小镇_阅读 224评论 0 0