AJAX與JSON

1. ajax

  • Ajax (Asynchronous Javascript And XML,異步 JavaScript 和 XML),是指一種創建交互式網頁應用的網頁開發技術。通過在後臺與服務器進行少量數據交換,Ajax 可以使網頁實現異步更新,即在不重新加載整個頁面的情況下,實現對網頁部分更新的效果。

  • 應用場景

    • 檢查用戶名是否已被註冊
    • 省市二聯下拉框聯動
    • 內容自動補全

1.1 同步方式與異步方式的區別

  • 同步方式發送請求

    • 每個請求都需要等待響應返回後才能發送下一個請求。如果請求無響應,則不能發送下一個請求,客戶端處於抑制等待的過程。
  • 異步方式發送請求

    • 每個請求不需要等待響應返回隨時可以發送下一個請求

1.2 ajax原理分析

  • 本質是js,通過對網頁的js代碼進行操作,達到頁面更新的效果。

  • 原理詳述:

    • ajax引擎提交異步請求,服務器端處理完返回數據給ajax引擎

2. js原生的ajax

2.1 js原生的ajax的開發步驟

1)創建Ajax引擎對象;
2)爲Ajax引擎對象綁定監聽(監聽服務器已將數據響應給引擎);
3)綁定提交地址;
4)發送請求;
5)接受響應數據。

2.2 原理

  • ajax通過ajax引擎對象與服務器通信狀態碼xmlHttp.readystate獲得連接狀態,狀態碼範圍:0-4。

  • 狀態碼的數值每次變化都會調用ajax的回調函數。

    0: 請求未初始化

    1: 服務器連接已建立

    2: 請求已接收

    3: 請求處理中

    4: 請求已完成,且響應已就緒

  • 只有ajax引擎通信狀態碼爲4和http通信狀態碼爲200才能保證獲得正確的響應數據

2.3 js原生的ajax示例代碼

html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style type="text/css"></style>
    <script type="text/javascript">
        //同步事件
        function sendRequest() {
            location.href="Demo01AjaxServlet?name=admin&psw=13579";
        }
        //異步事件
        function sendAjaxRequest() {
            //1)創建Ajax引擎對象;
            var xmlhttp = new XMLHttpRequest(); //此時readystate=0
            //2)爲Ajax引擎對象綁定監聽(監聽服務器已將數據響應給引擎);
            xmlhttp.onreadystatechange = function () {
                //狀態碼每次變動都會執行該函數
                //這個回調函數共被調用4次,但只有狀態碼4的時候才代表服務器響應數據完成。
                //只有保證ajax引擎通信狀態碼爲4和http通信狀態碼爲200,才能保證數據正確響應
                if (xmlhttp.readyState == 4 && xmlhttp.status==200) {
                    //5)獲得響應數據
                    var resultContent = xmlhttp.responseText;
                    alert(resultContent);
                }
            }
            //3)綁定提交地址;
            //xmlhttp.open(提交方式,請求路徑)
            xmlhttp.open("get","Demo01AjaxServlet?name=admin&psw=13579");
            //4)發送請求;
            xmlhttp.send();
        }
    </script>
</head>
<body>
<input type="button" value="發送同步請求" onclick="sendRequest()">
<input type="button" value="發送異步請求" onclick="sendAjaxRequest()">
</body>
</html>

servlet:已有過濾器過濾亂碼

@javax.servlet.annotation.WebServlet(urlPatterns = "/Demo01AjaxServlet")
public class Demo01AjaxServlet extends javax.servlet.http.HttpServlet {

    protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
        //獲得請求數據
        String name = request.getParameter("name");
        String psw = request.getParameter("psw");

        System.out.println("name=" + name);
        System.out.println("psw=" + psw);

        //輸出數據到頁面中
        response.getWriter().write("this is ajax");
    }

    protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
        //*如果post方式的執行內容與get不同,則刪掉下面代碼重寫即可
        doGet(request, response);
    }
}

3. jQuery框架下的ajax

3.1 jQuery框架的ajax簡介

以下爲常用的5種方式

請求方式 語法
GET請求 $.get(url, [data], [callback], [type])
POST請求 $.post(url, [data], [callback], [type])
AJAX請求 $.ajax([settings])
GET請求 $.get([settings])
POST請求 $.post([settings])

3.2 GET請求方式

  • 通過遠程 HTTP GET 請求載入信息

3.2.1 GET請求方式語法

  • jQuery.get(url, [data], [callback], [type])

參數說明:

參數名稱 解釋
url(必選) 請求的服務器端url地址
data 發送給服務器端的請求參數,格式是鍵值對字符串("key1=value1&key2=value2..."),或js對象({key1:value1,key2:value2...}
callback 請求成功後的回調函數,用於處理服務器返回的數據,格式爲function(result){},其中result是用於接收返回數據的變量
type 設置服務器返回數據的類型,常見類型有 xml, html, script, json, text(默認格式)等
注意事項

如果type是json,會要求服務器返回json字符串並將返回的數據轉換爲js對象(也稱爲json對象)。json字符串格式:"{\"key1\":value1,\"key2\":value2...}"。注意,json格式要求每個key必須使用雙引號括住。

3.2.3 GET請求示例代碼

html代碼

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>ajax</title>
    <style type="text/css"></style>
    <script type="text/javascript" src="js/jquery-3.3.1.min.js"></script>
    <script type="text/javascript">
        function sendAjaxRequest() {
            //使用get請求方式
            //jQuery.get(url, [data], [callback], [type])
            //注意,url、data、type都是字符串形式,callback的格式爲function(result){}
            $.get("Demo02AjaxServlet","name=admin&psw=13579",function (result) {
                alert(result);
            },"text");
        }
    </script>
</head>
<body>
<input type="button" value="發送異步請求" onclick="sendAjaxRequest()">
</body>
</html>

servlet代碼

@WebServlet(urlPatterns = "/Demo02AjaxServlet")
public class Demo02AjaxServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //獲得請求數據
        String name = request.getParameter("name");
        String psw = request.getParameter("psw");

        System.out.println("name=" + name);
        System.out.println("psw=" + psw);

        //輸出數據到頁面中
        response.getWriter().write("this is ajax by get");
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //獲得請求數據
        String name = request.getParameter("name");
        String psw = request.getParameter("psw");

        System.out.println("name=" + name);
        System.out.println("psw=" + psw);

        //輸出數據到頁面中
        response.getWriter().write("this is ajax by post");
    }
}

3.3 POST請求方式

  • 通過遠程 HTTP POST 請求載入信息

3.2.1 POST請求方式語法

  • jQuery.post(url, [data], [callback], [type])

參數說明同GET請求方式的參數說明

3.2.3 POST請求示例代碼

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>ajax</title>
    <style type="text/css"></style>
    <script type="text/javascript" src="js/jquery-3.3.1.min.js"></script>
    <script type="text/javascript">
        function sendAjaxRequest() {
            //使用post請求方式
            //jQuery.post(url, [data], [callback], [type])
            //注意,url、data、type都是字符串形式,callback的格式爲function(result){}
            $.post("Demo02AjaxServlet","name=admin&psw=13579",function (result) {
                alert(result);
            },"text");
        }
    </script>
</head>
<body>
<input type="button" value="發送異步請求" onclick="sendAjaxRequest()">
</body>
</html>

3.3 AJAX請求方式(也稱爲AJAX簽名方式)(推薦)

  • 通過 HTTP 請求加載遠程數據

3.3.1 AJAX請求方式語法

  • jQuery.ajax(url[,async][,data][,type][,dataType][,success][,error])
  • ajax的屬性要以js對象形式或鍵值對形式
屬性名稱 解釋
url(必選) 請求的服務器端url地址
async (默認: true) 默認設置下,所有請求均爲異步請求。如果需要發送同步請求,請將此選項設置爲 false
data 發送到服務器的數據,可以是鍵值對形式,也可以是js對象形式
type (默認: “GET”) 請求方式 (“POST” 或 “GET”), 默認爲 “GET”
dataType 預期的返回數據的類型,取值可以是 xml, html, script, json, text, _defaul
success 請求成功後的回調函數,一般格式function(result){}
error 請求失敗時調用此函數
注意事項

ajax請求方式的參數type含義與get/post請求方式的type含義不一樣,注意區分。

3.3.2 AJAX請求示例代碼

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>ajax</title>
    <style type="text/css"></style>
    <script type="text/javascript" src="js/jquery-3.3.1.min.js"></script>
    <script type="text/javascript">
        function sendAjaxRequest() {
            //使用ajax請求方式
            //jQuery.ajax(url[,async][,data][,type][,dataType][,success][,error])
            $.ajax({
                url:"Demo02AjaxServlet",
                data:{name:"admin",psw:"13579"},
                type:"get",//可以是get或者post
                dataType:"text",
                success:function (result) {
                    alert(result);
                },
                error:function () {
                    alert("服務器忙");
                }
            });

        }
    </script>
</head>
<body>
<input type="button" value="發送異步請求" onclick="sendAjaxRequest()">
</body>
</html>

3.4 jQuery3.0 的GET新增簽名方式

  • jQuery 3 爲jQuery.get()jQuery.post() 這兩個工具函數增加了新簽名,從而使得它們和 $.ajax() 的接口風格保持一致

3.4.1 jQuery3.0 的GET新增簽名方式語法

  • jQuery.get([settings])

注:settings與ajax請求方式的settings基本一致,除了不用寫type

示例代碼
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>ajax</title>
    <style type="text/css"></style>
    <script type="text/javascript" src="js/jquery-3.3.1.min.js"></script>
    <script type="text/javascript">
        function sendAjaxRequest() {
            //使用get新特性請求方式
            //jQuery.get(url[,async][,data][,type][,dataType][,success][,error])
            $.get({
                url:"Demo02AjaxServlet",
                data:{name:"admin",psw:"13579"},
                type:"get",
                dataType:"text",
                success:function (result) {
                    alert(result);
                },
                error:function () {
                    alert("服務器忙");
                }
            });

        }
    </script>
</head>
<body>
<input type="button" value="發送異步請求" onclick="sendAjaxRequest()">
</body>
</html>

3.4.2 jQuery3.0 的POST新增簽名方式語法

  • jQuery.post([settings])

注:settings與ajax請求方式的settings基本一致,除了不用寫type

示例代碼
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>ajax</title>
    <style type="text/css"></style>
    <script type="text/javascript" src="js/jquery-3.3.1.min.js"></script>
    <script type="text/javascript">
        function sendAjaxRequest() {
            //使用post新特性請求方式
            //jQuery.post(url[,async][,data][,type][,dataType][,success][,error])
            $.post({
                url:"Demo02AjaxServlet",
                data:{name:"admin",psw:"13579"},
                type:"get",
                dataType:"text",
                success:function (result) {
                    alert(result);
                },
                error:function () {
                    alert("服務器忙");
                }
            });

        }
    </script>
</head>
<body>
<input type="button" value="發送異步請求" onclick="sendAjaxRequest()">
</body>
</html>

3.5 使用jQuery框架下的ajax的注意事項

參數的value是字符串類型、js對象或者函數。如果不是js對象或者函數,基本都要用雙引號括住

4. JSON

  • JSON(JavaScript Object Notation, JS 對象標記) 是一種輕量級的數據交換格式。它基於ECMAScript的一個子集,採用完全獨立於編程語言的文本格式來存儲和表示數據。
  • 作用:
    • 處理Javascript 和web服務器端的之間數據交換,是一種數據傳輸格式
    • 常用於ajax,可以轉換成js對象

4.0.1 json字符串基本格式

  • "{\"key1\":value1,\"key2\":value2...}"
  • 注意,json格式要求每個key必須使用雙引號括住。

4.1 三種類型的json的語法格式

類型 語法 解釋
對象類型 {name:value,name:value...} 其中name是字符串類型(需要用雙引號括住),而value是任意類型
數組/集合類型 [value,value,value...][{},{}...] 其中value是任意類型
混合類型 {name:[]...} 合理包裹嵌套對象類型和數組類型

4.2 json示例代碼

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style type="text/css"></style>
    <script type="text/javascript">
        //json的定義
        var person = {"firstname":"張","lastname":"三豐","age":100};

        //json解析
        alert("1" + person.firstname);
        alert("1" + person.lastname);
        alert("1" + person.age);

        //[{key:value,key:value},{key:value,key:value}]
        var json = [
            {"firstname":"張","lastname":"三豐","age":100},
            {"firstname":"張","lastname":"翠山","age":58},
            {"firstname":"張","lastname":"無忌","age":23}
        ];

        for(var i=0;i<json.length;i++){
            alert("2" + json[i].lastname);
        }

        /*
        {
     *   "param":[{key:value,key:value},{key:value,key:value}]
     * }

         */
        json = {
            "baobao":[
                {"name":"小雙","age":18,"addr":"揚州"},
                {"name":"建寧","age":18,"addr":"北京海淀"},
                {"name":"龍兒","age":38,"addr":"島國"},
                {"name":"阿珂","age":17,"addr":"臺灣"}
            ]
        };

        //全取
        for(i=0;i<json.baobao.length;i++){
            alert("3" + json.baobao[i].name);
        }

        /*
        {
     *   "param1":[{key:value,key:value},{key:value,key:value}],
     *   "param2":[{key:value,key:value},{key:value,key:value}],
     *   "param3":[{key:value,key:value},{key:value,key:value}]
     * }
         */
        json = {
            "baobao":[
                {"name":"小雙","age":18,"addr":"揚州"},
                {"name":"建寧","age":18,"addr":"北京海淀"},
                {"name":"龍兒","age":38,"addr":"島國"},
                {"name":"阿珂","age":17,"addr":"臺灣"}
            ],
            "haohao":[
                {"name":"楠楠","age":23,"addr":"北京昌平修正"},
                {"name":"倩倩","age":18,"addr":"上海"}
            ]
        }


        //取倩倩
        alert(json.haohao[1].name);


    </script>
</head>
<body>

</body>
</html>

4.3 json轉換工具

  • json字符串拼接非常麻煩,首先每個key必須使用雙引號括住,而且整個字符串要用雙引號括住(詳見上面json格式),涉及到雙引號的轉義。如果字符串太長,很容易拼錯。

  • json的轉換工具是通過java封裝好的一些jar工具包,直接將java對象或集合轉換成json格式的字符串

4.3.1 常見的json轉換工具

Jsonlib: Java 類庫,需要導入的jar包較多
Gson: google提供的一個簡單的json轉換工具
Fastjson :alibaba技術團隊提供的一個高性能的json轉換工具
Jackson: 開源免費的json轉換工具,springmvc轉換默認使用jackson

4.3.2 開發步驟

1)導入json相關jar包;
2)創建java對象或集合;
3) 使用jackson的核心對象ObjectMapperwriteValueAsString()轉換爲json字符串

4.3.3 json轉換工具的返回值

  • 傳入java對象,返回值是對象類型的json字符串;
  • 傳入List集合,返回值是數組類型的json字符串(保存多條數據);
  • 傳入map集合,返回值是混合類型的json字符串;

4.3.4 json轉換示例代碼

public class Demo03Json_Jackson {
    public static void main(String[] args) {
        /*創建java對象或集合;
        使用Jackson的核心對象ObjectMapper的writeValueAsString()轉換爲json字符串*/

        try {
            //1.將JavaBean轉換爲json字符串
            //創建對象
            User user = new User(1,"JoJo","starplatinum");
            //使用Jackson核心對象轉換爲json字符串
            String jsonUser = new ObjectMapper().writeValueAsString(user);
            System.out.println("java對象轉json字符串:" + jsonUser);

            //2.將List轉換爲json字符串
            List<User> list = new ArrayList<>();
            list.add(new User(1,"JoJo","starplatinum"));
            list.add(new User(2,"dio","theworld"));
            //使用Jackson核心對象轉換爲json字符串
            String listJson = new ObjectMapper().writeValueAsString(list);
            System.out.println("List集合轉json字符串:" + listJson);

            //3.將Map轉換爲json字符串
            Map<String,User> map = new HashMap<>();
            map.put("jj", new User(1,"JoJo","starplatinum"));
            map.put("dd", new User(2,"dio","theworld"));
            //使用Jackson核心對象轉換爲json字符串
            String mapJson = new ObjectMapper().writeValueAsString(map);
            System.out.println("map集合轉json字符串:" + mapJson);

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

5. 經典案例

5.1 檢查用戶名是否已被註冊

需求:在用戶註冊頁面,輸入用戶名,當用戶名輸入框失去焦點時,發送異步請求,將輸入框的用戶名傳遞給服務器端進行是否存在的校驗。

準備工作:導入druid、JDBCUtils工具類、JdbcTemplate、tomcat及Tomcat8的亂碼過濾器、實體類

5.1.1 頁面代碼

  • 重點:使用ajax異步請求數據,注意,每個屬性的值是字符串或者js對象,success和error屬性是回調函數,success的需要用一個變量保存返回的數據
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>register</title>
    <style type="text/css"></style>
    <script type="text/javascript" src="js/jquery-3.3.1.min.js"></script>
    <script type="text/javascript">
        /*
        思路:給用戶名的input註冊一個失去焦點的事件,當觸發事件後異步發送請求到服務器中查詢
        獲取返回的信息輸出信息(使用json和ajax)
         */
        //註冊失去焦點事件
        $(function () {
            $("#username").blur(function () {
                //獲取用戶輸入的內容
                var content = $(this).val();
                //判斷輸入的內容是否爲空,空返回false,非空返回true
                if (content){
                    //使用ajax異步發送請求
                    $.ajax({
                        url: "RegisterServlet",
                        data:{username:content},    //注意是一個js對象或者鍵值對
                        type:"post",
                        dataType:"json",
                        success:function (result) {
                            /*如果是用戶名存在,則顯示紅色字體*/
                            if(result.flag) {
                                $("#usernameInfo").css("color","red");
                            } else {
                                /*如果是用戶名不存在,則顯示綠色字體*/
                                $("#usernameInfo").css("color","green");
                            }
                            //在輸入框後面的span標籤添加msg內容
                            $("#usernameInfo").html(result.msg);
                        },
                        error:function () {
                            alert("服務器忙,請稍後")
                        }
                    });
                }

            });
        });
    </script>

</head>
<body>
<div>
    <font>會員註冊</font>USER REGISTER
    <form class="form-horizontal" style="margin-top: 5px;">
        <table>
            <tr>
                <td>用戶名</td>
                <td>
                    <input type="text" id="username" name="username" placeholder="請輸入用戶名">
                    <span id="usernameInfo" style="color:red"></span>
                </td>
            </tr>
            <tr>
                <td>密碼</td>
                <td>
                    <input type="password" placeholder="請輸入密碼">
                </td>
            </tr>
        </table>
        <input type="submit" value="註冊"/>
    </form>
</div>

</body>
</html>

5.1.2 web層

重點:拼接json字符串,用於給頁面顯示提示信息

@WebServlet(urlPatterns = "/RegisterServlet")
public class RegisterServlet extends HttpServlet {

    private RegisterService service = new RegisterService();

    /*
    思路:頁面發送請求到這裏,調用service層的方法獲得數據,然後返回json數據,其中包含兩個屬性,第一個是布爾類型,
    用於指明用戶名是否存在,第二個是String類型,用於給予對應的提示
     */

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            //獲取請求的數據
            String username = request.getParameter("username");
            //根據username調用方法獲取對應的用戶
            User user = service.getUserByName(username);
            String jsonData = null;
            //判斷user是否爲空
            if (user != null) {
                //拼接json字符串
                jsonData = "{\"flag\":true,\"msg\":\"已被註冊\"}";//js對象
            } else {
                jsonData = "{\"flag\":false,\"msg\":\"可以註冊\"}";//js對象
            }
            //返回json到頁面
            response.getWriter().write(jsonData);
        } catch (Exception e) {
            e.printStackTrace();
            //不需要給前端友好提示,因爲前端有錯誤回調函數,這裏只要不返回json字符串,ajax引擎就知道發生錯誤了。
        }

    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //*如果post方式的執行內容與get不同,則刪掉下面代碼重寫即可
        doGet(request, response);
    }
}

5.1.3 service層

public class RegisterService {

    private UserDao userDao = new UserDao();

    /**
     * 調用dao層獲取用戶
     * @param username
     * @return User
     * @throws Exception
     */
    public User getUserByName(String username) throws Exception{
        return userDao.getUserByName(username);
    }
}

5.1.4 dao層

public class UserDao {

    private JdbcTemplate jdbcTemplate = new JdbcTemplate(JDBCUtils.getDataSource());

    /**
     * 訪問數據庫獲取用戶信息
     * @param username
     * @return User
     * @throws SQLException
     */
    public User getUserByName(String username) throws SQLException{
        try {
            String sql = "select * from user where username = ?;";
            return jdbcTemplate.queryForObject(sql,new BeanPropertyRowMapper<>(User.class),username);
        } catch (DataAccessException e) {
            return null;
        }
    }
}

5.2 內容自動補全

需求:在輸入框輸入關鍵字,下拉框中異步顯示與該關鍵字相關的商品的名稱

案例代碼
  • 下面代碼已省略實體類、亂碼過濾器、工具類等準備工作

5.2.1 jsp頁面

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Insert title here</title>
    <style type="text/css">
        .content{
            width:643px;
            margin:200px auto;
            text-align: center;
        }
        input[type='text']{
            width:530px;
            height:40px;
            font-size: 14px;
        }
        input[type='button']{
            width:100px;
            height:46px;
            background: #38f;
            border: 0;
            color: #fff;
            font-size: 15px
        }
        .show{
            position: absolute;
            width: 535px;
            height:100px;
            border: 1px solid #999;
            border-top: 0;
            display: none;
        }
    </style>
    <script type="text/javascript" src="js/jquery-3.3.1.min.js"></script>
    <script type="text/javascript">
        $(function () {
            //給搜索框註冊鍵盤彈起事件
            $("#word").keyup(function () {
                //獲取搜索框的內容
                var content = $(this).val();
                //判斷有效性,如果不爲空則異步發送請求
                if (content) {
                    //使用ajax異步發送請求
                    $.ajax({
                        url:"SearchServlet",
                        data:{word:content},    //傳輸的數據時輸入的內容
                        dataType:"json",
                        type:"post",
                        success:function (result) {
                            //如果獲得數據,則將數據添加到輸入框後面,需要拼裝字符串
                            //遍歷,獲取列表每個數據並拼裝
                            var html = "";
                            for (var i=0;i<result.length;i++) {
                                //獲取每個user數據
                                var user=result[i];
                                //拼接字符串
                                html+="<div>"+user.name+"</div>"
                            }
                            //將拼接的字符串更新到show的標籤體中
                            $(".show").html(html);
                            //使用動畫將更新的內容顯示出來
                            $(".show").show();
                        },
                        error:function () {
                            alert("服務器忙,請稍後再試");
                        }
                    });
                }
            });
        });
    </script>
</head>
<body>
<div class="content">
    <img alt="" src="img/管理三連.jpg"><br/><br/>
    <input id="word" type="text" name="word">
    <input type="button" value="搜索一下">
    <div class="show"></div>
</div>
</body>
</html>

5.2.2 web層

@WebServlet(urlPatterns = "/SearchServlet")
public class SearchServlet extends HttpServlet {

    private SearchService searchService = new SearchService();

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            //獲取請求數據
            String content = request.getParameter("word");
            //調用service層獲取符合條件的列表
            List<User> userList = searchService.findContent(content);
            //轉化爲json返回到瀏覽器
            String listStr = new ObjectMapper().writeValueAsString(userList);
            response.getWriter().write(listStr);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}

5.2.3 service層

public class SearchService {
    private UserDao userDao = new UserDao();
    /**
     * 獲得user列表
     * @param content
     * @return List<User>
     * @throws Exception
     */
    public List<User> findContent(String content) throws Exception{
        return userDao.findContent(content);
    }
}

5.2.4 dao層

public class UserDao {
    private JdbcTemplate jdbcTemplate = new JdbcTemplate(JDBCUtils.getDataSource());
    /**
     * 獲得相關的user列表
     * @param content
     * @return List<User>
     * @throws SQLException
     */
    public List<User> findContent(String content) throws SQLException{
        String sql = "select * from user where name like ? limit 0,4;"; //限制顯示0-4條
        return jdbcTemplate.query(sql,new BeanPropertyRowMapper<>(User.class),content+"%");   //模糊搜索,獲得已content開頭的列表
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章