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