在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 教程/ Linux/ Servlet查詢搜索數(shù)據(jù)示例
Servlet web.xml welcome-file-list
Servlet從數(shù)據(jù)庫讀取記錄性能優(yōu)化
Servlet URL重寫帶參數(shù)
War文件
Web技術(shù)基礎(chǔ)
Servlet GenericServlet類
Servlet API
Servlet ServletInputStream類
使用MyEclipse創(chuàng)建Servlet
Servlet增刪改查
Servlet ServletConfig配置信息
Servlet Cookies
Servlet重定向
Servlet生命周期
Servlet HttpSession會話
Servlet HttpServlet類
Servlet注冊表單示例
Servlet表單隱藏字段
Servlet下載文件
Servlet教程
Servlet身份驗證過濾器
Servlet ServletOutputStream類
Servlet HttpSession登錄注銷實例
Servlet啟動時加載
Servlet事件和監(jiān)聽器
使用Eclipse創(chuàng)建Servlet
Servlet ServletContextEvent事件
Servlet HttpSessionEvent統(tǒng)計在線用戶數(shù)實例
Servlet RequestDispatcher請求轉(zhuǎn)發(fā)
Servlet使用注釋
Servlet過濾器示例
Servlet過慮器
Servlet ServletContext配置信息
Servlet登錄注銷Cookies實例
Servlet工作流程
Servlet會話跟蹤
Servlet登錄實例
Servlet ServletRequest接口
Servlet ServletRequestEvent類和接口
Servlet入門程序
Servlet查詢搜索數(shù)據(jù)示例
Servlet FilterConfig應(yīng)用示例
Servlet顯示所有頭信息
Servlet屬性設(shè)置
使用NetBeans創(chuàng)建Servlet
Servlet接口實現(xiàn)
Servlet上傳文件

Servlet查詢搜索數(shù)據(jù)示例

在這里,您將學習如何按給定關(guān)鍵字搜索對應(yīng)數(shù)據(jù)庫表字段的結(jié)果。假設(shè)有一個表的結(jié)構(gòu)和數(shù)據(jù)記錄如下:

DROP TABLE IF EXISTS `servlet_user`;
CREATE TABLE `servlet_user` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(64) NOT NULL DEFAULT '',
  `passwd` varchar(32) NOT NULL DEFAULT '',
  `email` varchar(32) DEFAULT NULL,
  `city` varchar(24) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of servlet_user
-- ----------------------------
INSERT INTO `servlet_user` VALUES ('1', 'maxsu', '123456', 'maxsu@yiibai.com', '廣州');
INSERT INTO `servlet_user` VALUES ('2', 'minsu', '233123', 'minsu@gmail.com', '???#39;);
INSERT INTO `servlet_user` VALUES ('3', 'avguser', 'fdsa123', 'avguser@qq.com', '廣州');
INSERT INTO `servlet_user` VALUES ('4', 'sumuser', 'fdsj124', 'sumuser@qq.com', '北京');

在這個例子中,我們從servlet中查詢數(shù)據(jù)庫servlet_user表中的數(shù)據(jù)并將結(jié)果打印。為了簡化程序,我們在Servlet中執(zhí)行所有數(shù)據(jù)庫操作邏輯。但在現(xiàn)實應(yīng)用中最好將它與servlet文件分開,如把數(shù)據(jù)庫操作部分放到獨立的DAO文件中。

按給定關(guān)鍵字搜索的示例

打開Eclipse,創(chuàng)建一個動態(tài)Web項目:SearchExample,其完整的目錄結(jié)構(gòu)如下所示 -

以下是這個項目中的幾個主要的代碼文件。

在這個例子中,創(chuàng)建了以下幾個文件 -

  • index.html - 表單顯示
  • Search.java - 執(zhí)行輸入關(guān)鍵字收集,連接數(shù)據(jù)庫和查詢操作的Servlet類。
  • web.xml - 項目Servlet的配置和描述符文件。

文件:index.html

該頁面顯示從用戶輸入的關(guān)鍵字的表單,并將此數(shù)據(jù)轉(zhuǎn)發(fā)到servlet,servlet負責根據(jù)給定的關(guān)鍵字查詢表中的數(shù)據(jù)記錄并顯示結(jié)果。

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>根據(jù)關(guān)鍵字搜索示例</title>
</head>
<body>
    <div style="margin: 0px; text-align: center;">
        <form action="search">
            關(guān)鍵字:<input type="text" name="keyword" /><input type="submit"
                value="搜索" />
        </form>
    </div>
</body>
</html>

文件:Search.java

這是根據(jù)用戶輸入關(guān)鍵字,然后查詢數(shù)據(jù)庫中相關(guān)記錄并打印匹配數(shù)據(jù)的記錄的servlet文件。 在這個頁面中,我們顯示數(shù)據(jù)庫的列名和數(shù)據(jù),所以使用ResultSetMetaData接口。

package com.yiibai;

import java.io.*;
import java.sql.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;

public class Search extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        request.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();

        String keyword = request.getParameter("keyword");
        //int keyword = Integer.valueOf(keyword);
        if(keyword==null) {
            keyword = "";
        }
        try {
            Connection con = null;
            try {
                Class.forName("com.mysql.jdbc.Driver");
                con = DriverManager.getConnection("jdbc:mysql://localhost/testdb?useSSL=false&characterEncoding=utf8",
                        "root", "123456");
            } catch (Exception e) {
                System.out.println(e);
            }

            PreparedStatement ps = con.prepareStatement("SELECT * FROM `servlet_user` where name LIKE ?");
            ps.setString(1, "%"+keyword+"%");

            out.print("<table width=50% border=1>");
            out.print("<caption>Result:</caption>");

            ResultSet rs = ps.executeQuery();

            /* 打印表字段的名稱 */
            ResultSetMetaData rsmd = rs.getMetaData();
            int total = rsmd.getColumnCount();
            out.print("<tr>");
            for (int i = 1; i <= total; i++) {
                out.print("<th>" + rsmd.getColumnName(i) + "</th>");
            }
            out.print("</tr>");

            /* Printing result */

            while (rs.next()) {
                out.print("<tr><td>" + rs.getInt(1) + "</td><td>" + rs.getString(2) + "</td><td>" + rs.getString(3)
                        + "</td><td>" + rs.getString(4) + "</td><td>" + rs.getString(5) + "</td></tr>");

            }
            out.print("</table>");

        } catch (Exception e2) {
            e2.printStackTrace();
        }

        finally {
            out.close();
        }

    }
}

文件:web.xml

這是向容器提供servlet信息的配置文件。

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
    id="WebApp_ID" version="3.1">
    <display-name>SearchExample</display-name>
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
    <servlet>
        <servlet-name>Search</servlet-name>
        <servlet-class>com.yiibai.Search</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>Search</servlet-name>
        <url-pattern>/search</url-pattern>
    </servlet-mapping>
</web-app>

在編寫上面代碼后,部署此Web應(yīng)用程序(在項目名稱上點擊右鍵->”Run On Server…”),打開瀏覽器訪問URL: http://localhost:8080/SearchExample/ ,如果沒有錯誤,應(yīng)該會看到以下結(jié)果 -

在上面關(guān)鍵字輸入框中輸入:su,然后提交搜索,得到以下結(jié)果 -