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