SpringMVC學習(五)

AJAX

一、AJAX簡介

  • AJAX = Asynchronous JavaScript and XML(異步的JavaScript 和 XML);
  • AJAX不是新的編程語言,而是一種使用現有標準的新方法;
  • AJAX最大的優勢式在不從新加載整個頁面的狀況下,能夠與服務器交換數據並更新部分網頁內容;
  • AJAX不須要任何瀏覽器插件,可是須要用戶容許JavaScript在瀏覽器上執行。
  • 傳統的網頁(即不用ajax技術的網頁),想要更新內容或者提交一個表單,都須要加載整個網頁
  • 使用ajax技術的網頁,經過在後臺服務器進行少許的數據交換,就能夠實現異步局部更新。
  • 使用Ajax,用戶能夠建立接近本地桌面應用的直接、高可用、更豐富、更動態的Web用戶界面。

二、僞造Ajax

咱們可使用前端的一個標籤來僞造一個ajax的樣子。iframe標籤javascript

一、新建項目,導入web支持

二、編寫一個html頁面,使用iframe測試

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>ajax初體驗</title>

    <script>
        function f() {
            //獲取url框的value即url
            var url = document.getElementById("url").value;
            //將獲取到的url賦值給iframe的屬性src
            document.getElementById("iframe").src=url;
        }
    </script>

</head>
<body>

<div>
    <p>請輸入地址:</p>
    <input type="url" id="url">
    <!--onclick 按下按鈕發生的事件-->
    <input type="button" id="button" value="提交" onclick="f()">
</div>
<div>
    <iframe id="iframe" style="width: 100%;height: 500px" ></iframe>
</div>

</body>
</html>

測試:url中輸入嗶哩嗶哩的網址,點擊提交按鈕css

三、利用AJAX能夠作的事

  • 註冊時,輸入用戶名自動檢測用戶是否已經存在;
  • 登錄時,提示用戶密碼錯誤;
  • 刪除數據行,將行ID發送到後臺,後臺在數據庫中刪除,數據庫刪除成功後,在頁面DOM中將數據行也刪除;
  • ......等等

四、jQuery.ajax

  • 使用jquery提供的ajax,方便學習和使用,避免重複造輪子;
  • Ajax的核心是XMLHttpRequest對象(XHR)。XHR爲像服務器發送請求和解析服務器提供了接口。可以以衣服方式從服務器獲取新數據
  • jQuery提供多個與AJAX有關的方法
  • 經過jQuery AJAX方法,可以使用HHTP Get 和 Post從遠程服務器上請求文本、HTML、XML或JSON;
  • jQuery Ajax本質就是 XMLHttpRequest,對他進行了封裝,方便調用!
jQuery.ajax(...)
       部分參數:
              url:請求地址
             type:請求方式,GET、POST(1.9.0以後用method)
          headers:請求頭
             data:要發送的數據
      contentType:即將發送信息至服務器的內容編碼類型(默認: "application/x-www-form-urlencoded; charset=UTF-8")
            async:是否異步
          timeout:設置請求超時時間(毫秒)
       beforeSend:發送請求前執行的函數(全局)
         complete:完成以後執行的回調函數(全局)
          success:成功以後執行的回調函數(全局)
            error:失敗以後執行的回調函數(全局)
          accepts:經過請求頭髮送給服務器,告訴服務器當前客戶端課接受的數據類型
         dataType:將服務器端返回的數據轉換成指定類型
            "xml": 將服務器端返回的內容轉換成xml格式
           "text": 將服務器端返回的內容轉換成普通文本格式
           "html": 將服務器端返回的內容轉換成普通文本格式,在插入DOM中時,若是包含JavaScript標籤,則會嘗試去執行。
         "script": 嘗試將返回值看成JavaScript去執行,而後再將服務器端返回的內容轉換成普通文本格式
           "json": 將服務器端返回的內容轉換成相應的JavaScript對象
          "jsonp": JSONP 格式使用 JSONP 形式調用函數時,如 "myurl?callback=?" jQuery 將自動替換 ? 爲正確的函數名,以執行回調函數

咱們進行一個簡單的測試,使用最原始的HttpServletRequest處理1html

一、編寫的配置文件

web.xml前端

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

    <servlet>
        <servlet-name>DispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--關聯一個SpringMVC的配置文件-->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc-servlet.xml</param-value>
        </init-param>
        <!--服務器啓動的時候就啓動-->
        <load-on-startup>1</load-on-startup>
    </servlet>
    <!--
        /  匹配全部的請求  不包括.jsp
        /*  匹配全部的請求  包括.jsp
    -->
    <servlet-mapping>
        <servlet-name>DispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <filter>
        <filter-name>encoding</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>utf-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encoding</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

</web-app>

springmvc-servlet.xmljava

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc
        https://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd">

    <!--掃描包配置,控制層,和前端交互 controller-->
    <context:component-scan base-package="com.star.controller"/>
    <!--開啓註解掃描-->
    <mvc:annotation-driven/>
    <!--靜態資源過濾-->
    <mvc:default-servlet-handler/>

    <!--添加視圖解析器-->
    <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

</beans>

二、編寫一個AjaxController

package com.star.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@RestController
public class ajaxController {

    @RequestMapping("/t1")
    public void test2(String name, HttpServletResponse response) throws IOException {
        System.out.println("test2:param=>" + name);
        if ("lenStar".equals(name)){
            response.getWriter().print("true");
        }else{
            response.getWriter().print("false");
        }
    }

}

三、導入jQuery

可以使用在線的CDN,也能夠下載導入;jquery

<script src="${pageContext.request.contextPath}/statics/js/jquery-3.4.1.js"></script>

四、編寫index.jsp測試

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>

    <script src="${pageContext.request.contextPath}/statics/js/jquery-3.4.1.js"></script>

    <script>
      function a(){
          $.post({
              url:"${pageContext.request.contextPath}/t1",
              data:{"name":$("#username").val()},//這裏的data是傳給後端的值
              success:function (data,status) {
                  //這裏的data是後臺傳來的數據
                  console.log(data);
                  console.log(status)
              }
          });
      }
    </script>

  </head>
  <body>

  <%--失去焦點的時候發起一個請求(攜帶信息)到後臺--%>
  用戶名:<input type="text" id="username" onblur="a()">

  </body>
</html>

五、啓動tomcat測試!

打開瀏覽器的控制檯,當咱們鼠標離開輸入框的時候,能夠看到發出來一個ajax的請求!是後臺返回給咱們的結果!web

輸入lenStar時:ajax

五、SpringMVC實現

一、編寫實體類User

package com.star.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private String name;
    private int age;
    private String sex;
}

二、獲取一個集合對象,展現到前端頁面

@RequestMapping("/t2")
    public List<User> test3(){
        List<User> users = new ArrayList<User>();
        users.add(new User("張三",2,"男"));
        users.add(new User("李四",3,"女"));
        users.add(new User("王五",4,"男"));
        users.add(new User("趙六",5,"女"));
        return users;
    }

三、前端頁面test.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>

    <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    <script src="${pageContext.request.contextPath}/statics/js/jquery-3.4.1.js"></script>

    <script>
        $(function () {
            $("#btn").click(function () {
                $.post("${pageContext.request.contextPath}/t2", function (data) {
                    console.log(data);
                    var html ="";
                    for (let i = 0; i < data.length; i++) {
                        html += "<tr>" +
                            "<td>" + data[i].name + "</td>" +
                            "<td>" + data[i].age + "</td>" +
                            "<td>" + data[i].sex + "</td>" +
                            "</tr>"
                    }
                    $("#content").html(html);
                })
            })
        })
    </script>

</head>
<body>

<div class="container">

    <div class="row clearfix">
        <div class="col-md-12 column">
            <div class="page-header">
                <h1>
                    <small>用戶列表 —— 顯示全部用戶信息</small>
                </h1>
            </div>
        </div>
    </div>

    <div class="row">
        <div class="col-md-4 column">
            <input class="btn btn-primary" id="btn" type="button" value="加載數據">
        </div>
    </div>

    <div class="row clearfix">
        <div class="col-md-12 column">
            <table class="table table-hover table-striped">
                <thead>
                <tr>
                    <th>姓名</th>
                    <th>年齡</th>
                    <th>性別</th>
                </tr>
                </thead>
                <tbody id="content">
                </tbody>
            </table>
        </div>
    </div>
</div>

</body>
</html>

四、啓動測試:點擊按鈕獲取數據

六、註冊提示效果

咱們平時註冊時候,輸入框後面的實時提示怎麼作到的;如何優化?spring

一、Controller類

@RequestMapping("/t3")
    public String test4(String name,String pwd){
        String msg="";
        if(name!=null){
            if("lenStar".equals(name)){
                msg = "OK!";
            }else {
                msg = "用戶名錯誤!";
            }
        }
        if(pwd!=null){
            if("123456".equals(pwd)){
                msg = "OK!";
            }else {
                msg = "密碼錯誤!";
            }
        }
        return msg;
    }

二、前端登陸頁面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>

    <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    <script src="${pageContext.request.contextPath}/statics/js/jquery-3.4.1.js"></script>

    <script>
        function a1() {
            $.post({
                url:"${pageContext.request.contextPath}/t3",
                data:{"name":$("#name").val()},
                success:function (data) {
                    if(data.toString()==="OK!"){
                        $("#nameInfo").css("color","green")
                    }else {
                        $("#nameInfo").css("color","red")
                    }
                    $("#nameInfo").html(data)
                }
            })
        }
        function a2() {
            $.post({
                url:"${pageContext.request.contextPath}/t3",
                data:{"pwd":$("#pwd").val()},
                success:function (data) {
                    if(data.toString()==="OK!"){
                        $("#pwdInfo").css("color","green")
                    }else {
                        $("#pwdInfo").css("color","red")
                    }
                    $("#pwdInfo").html(data)
                }
            })
        }
    </script>

</head>
<body>
    <div class="container">
        <div class="row clearfix">
            <div class="col-md-12 column">
                <div class="page-header">
                    <h1>
                        <small style="padding-left: 400px">用戶登陸頁面</small>
                    </h1>
                </div>
            </div>
        </div>

        <form style="padding-left: 300px" class="form-horizontal" role="form">
            <div class="form-group">
                <label class="col-sm-2 control-label">用戶名</label>
                <div class="col-sm-10">
                    <input type="text" id="name" class="form-control" style="width: 300px" placeholder="請輸入用戶名" onblur="a1()">
                    <span id="nameInfo"></span>
                </div>

            </div>

            <div class="form-group">
                <label class="col-sm-2 control-label">密碼</label>
                <div class="col-sm-10">
                    <input type="password" class="form-control" style="width: 300px" id="pwd" placeholder="請輸入密碼" onblur="a2()">
                    <span id="pwdInfo"></span>
                </div>

            </div>

            <div class="form-group">
                <div class="col-sm-offset-2 col-sm-10">
                    <div class="checkbox">
                        <label>
                            <input  type="checkbox"> 記住我
                        </label>
                    </div>
                </div>
            </div>

            <div class="form-group">
                <div class="col-sm-offset-2 col-sm-10">
                    <button style="width: 300px" type="submit" class="btn btn-primary">登陸</button>
                </div>
            </div>
        </form>
    </div>
</body>
</html>

三、啓動測試

輸入不正確時:數據庫

輸入正確時:

**動態請求響應,局部刷新,就是如此!

相關文章
相關標籤/搜索