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,765評論 18 399
  • 這部分主要是與Java Web和Web Service相關的面試題。 96、闡述Servlet和CGI的區別? 答...
    雜貨鋪老板閱讀 1,425評論 0 10
  • Spring Cloud為開發人員提供了快速構建分布式系統中一些常見模式的工具(例如配置管理,服務發現,斷路器,智...
    卡卡羅2017閱讀 134,923評論 18 139
  • 作者:樊榮強 我發現,初入社會,初入職場的許多年輕人,常常為人際關系而感到困惑。而這些困惑當中,最突出的一個就是,...
    樊榮強閱讀 14,336評論 96 650
  • 開啟我的iOS路 我在大學所學的專業是.net,但是其實在大二時候我對編程基本上還處于一無所知的狀態。我也...
    小鎮_閱讀 224評論 0 0