天天看點

SpringMVC———Ajax—攔截器一、Ajax二、攔截器Interceptor

目錄

  • 一、Ajax
      • 練習一:指定使用者名,進行判斷,彈窗顯示
      • 練習二:點選顯示資料,在控制台顯示
      • 練習三:檢查使用者名是否存在,彈出資訊
      • 中文亂碼問題
  • 二、攔截器Interceptor
      • 過濾器Filter
      • 攔截器與過濾器差別
      • 攔截器步驟
      • 案例:登入驗證攔截

一、Ajax

  • 概念:Ajax 不是一種新的程式設計語言,而是一種用于建立更好更快以及互動性更強的Web應用程式的技術。
  • 作用:更新部分網頁,而不重新整理全部頁面。

練習一:指定使用者名,進行判斷,彈窗顯示

後端判斷
@RestController
public class AjaxController {
    @RequestMapping("/d1")
    public void demo01(String username, HttpServletResponse response, HttpServletRequest request) throws IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=UTF-8");
        System.out.println(username);
        if ("admin".equals(username)){
            response.getWriter().print("使用者名:admin");
        }else {
            response.getWriter().print("使用者名:未知");
        }
    }
           
前端顯示
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <script src="${pageContext.request.contextPath}/statics/js/jquery-3.5.1.js"></script>
    <script>
        function lost() {
            $.post({
                url:"${pageContext.request.contextPath}/d1",
                data:{"username":$("#username").val()},
                success:function (data) {
                    console.log(data);
                    alert(data);
                }
            });
        }
    </script>
</head>
<body>
<div>
    <input type="text" id="username" onblur="lost()">
</div>
</body>
</html>
           

練習二:點選顯示資料,在控制台顯示

後端判斷
@RequestMapping("/d2")
    public List<User> demo02(HttpServletResponse response, HttpServletRequest request) throws IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=UTF-8");
        User user01 = new User("張三", 3, 1);
        User user02 = new User("李四", 4, 2);
        User user03 = new User("王五", 5, 3);
        User user04 = new User("趙六", 6, 4);
        ArrayList<User> list = new ArrayList<User>();
        list.add(user01);
        list.add(user02);
        list.add(user03);
        list.add(user04);
        return list;
    }
           
前端頁面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>show</title>
    <script src="${pageContext.request.contextPath}/statics/js/jquery-3.5.1.js"></script>
    <script>
    function show() {
        console.log(123);
        $.post("${pageContext.request.contextPath}/d2",function (data) {
            console.log(data)
        });
    }
    </script>
</head>
<body>
<input type="button" id="btn" value="加載資料" onclick="show()">
<table class="tab" border="2px" width="600px" align="center">
    <tr>
        <th>使用者名</th>
        <th>密碼</th>
        <th>登入次數</th>
    </tr>
    <c:forEach var="list" items="${list}">
        <tr>
            <th> ${booklist.bookID}</th>
            <th>${list.name}</th>
            <th>${list.age}</th>
            <th>${list.loginCount}</th>
        </tr>
    </c:forEach>
</table>
</body>
</html>
           

練習三:檢查使用者名是否存在,彈出資訊

後端判斷
@RequestMapping(value = "/c1",produces={"text/html;charset=UTF-8;","application/json;"})
    public String demo03(String username,HttpServletResponse response, HttpServletRequest request) throws IOException {
        User user01 = new User("張三", 3, 1);
        User user02 = new User("李四", 4, 2);
        User user03 = new User("王五", 5, 3);
        User user04 = new User("趙六", 6, 4);
        ArrayList<User> list = new ArrayList<User>();
        list.add(user01);
        list.add(user02);
        list.add(user03);
        list.add(user04);
        System.out.println("使用者名:"+username);
        String msg=null;
        ArrayList<String> namelist = new ArrayList<String>();
        for (User user : list) {
            String name = user.getName();
            namelist.add(name);
        }
        System.out.println("已存在使用者:"+namelist);
        if (!(namelist.contains(username))){
            msg="OK";
        }else{
            msg="使用者名已存在";
        }
        System.out.println("檢查資訊:"+msg);
        return msg;
    }
           
前端頁面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>檢查使用者名</title>
    <script src="${pageContext.request.contextPath}/statics/js/jquery-3.5.1.js"></script>
    <script>
        function check() {
            $.post({
                url:"${pageContext.request.contextPath}/c1",
                data:{"username":$("#username").val()},
                success:function (data) {
                    console.log(data);
                    alert(data);
                }
            });
        }
    </script>
</head>
<body>
<div align="center">
    使用者名:<input type="text" id="username" onblur="check()">
</div>
</body>
</html>
           

中文亂碼問題

後端的資料通過Ajax上傳到前端頁面時出現亂碼

解決方法

在注解後添加produces={“text/html;charset=UTF-8;”,“application/json;”}

@RequestMapping(value = "/c1",produces={"text/html;charset=UTF-8;","application/json;"})
public String demo03(String username,HttpServletResponse response, HttpServletRequest request) throws IOException{
...
}
           
原因

注解是向ajax傳回json資料格式的值,預設編碼是“ISO-8859-1”,通過produces = {“application/json;charset=UTF-8”}來修改為utf-8編碼,這樣ajax接收到的資料就不會亂碼了。

二、攔截器Interceptor

  • 原理:依賴于web(SpringMVC)架構,實作是基于Java的反射機制
    • 攔截器是面向切面程式設計AOP的具體應用:在service包或一個方法前/後調用一個方法
  • 優點:一個攔截器執行個體在一個controller生命周期可以調用多次
  • 缺點:隻能對controller請求進行攔截

過濾器Filter

  • 原理:依賴于Servlet容器,實作是基于函數回調
  • 作用:過濾操作,擷取想要的資料。
  • 優點:可以對幾乎所有的請求進行過濾
  • 缺點:一個過濾器執行個體是能在容器初始化時調用一次。
  • 場景:
    1. SpringMVC自帶的CharacterEncodingFilter字元編碼
    1. 修改Request參數的自定義過濾器,需要在web.xml中映射

攔截器與過濾器差別

Filter的執行順序在Interceptor之前

執行順序:請求———>Filter———>Interceptor———>DispatcherServlet

  • Interceptor攔截器:功能更強大,Filter能做的事情,都能做,而且可以在請求前,請求後執行,比較靈活。
  • Filter過濾器:主要是針對URL位址做一個編碼的事情、過濾掉沒用的參數、安全校驗等。

攔截器步驟

  1. 編寫controller請求
@RestController
public class testController {

    @RequestMapping("/t01")
    public String test01(){
        System.out.println("測試請求01");
        return "測試通過";
    }
}
           
  1. 編寫攔截器
public class testInterceptor implements HandlerInterceptor {
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
       // return false; // 攔截請求,不放行
        System.out.println("========處理請求前========");
        return true; // 不攔截請求,放行

    }
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("========處理請求後========");

    }
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("========清理結束========");
    }
}
           
  1. 編寫配置檔案
<!--配置攔截器-->
    <mvc:interceptors>
        <mvc:interceptor>
           <!--配置攔截的路徑-->
            <mvc:mapping path="/**"/>
            <!--配置自定義攔截器内容-->
            <bean class="zy.interceptor.testInterceptor"/>
        </mvc:interceptor>
    </mvc:interceptors>
           

其中 /**:包括路徑及其子路徑

4. 運作及其結果

========處理請求前========
測試請求01
========處理請求後========
========清理結束========
           

案例:登入驗證攔截

  • 首頁
<body align="center">
  <h1>首頁</h1>
  <h1 style="color: lightpink">
    <a href="${pageContext.request.contextPath}/new/tologin">登陸頁面</a>
  </h1>

  <h1 style="color: skyblue">
    <a href="${pageContext.request.contextPath}/loginSuccess">登陸成功頁面</a>
  </h1>
</body>
           
  • controller請求
@Controller
public class loginController {

    @RequestMapping("/new/tologin")
    public String tologin(){
        return "login";
    }

    @RequestMapping("/loginSuccess")
    public String loginSuccess(){
        return "loginSuccess";
    }

    @RequestMapping("/new/login")
    public String login(HttpSession session, String username, String pwd){
        System.out.println("登入頁面");
        session.setAttribute("USERNAME",username);
        return "loginSuccess";
    }

    // 登出登入
    @RequestMapping("/logout")
    public String logout(HttpSession session, String username, String pwd){
        session.removeAttribute("USERNAME");
        return "login";
    }
}
           
  • 登入頁面
<body align="center">
<form action="${pageContext.request.contextPath}/new/login" method="post">
    使用者名:<input type="text" name="username">
    密碼:<input type="password" name="pwd">
    <input type="submit" value="登入">
</form>
</body>
           
  • 登入成功頁面
<body align="center">
<h1 style="color: salmon">進入登陸成功頁面</h1>
<h2>使用者名:${USERNAME}</h2>
<h2><a href="${pageContext.request.contextPath}/logout">登出</a></h2>
</body>
           
  • 登陸攔截器
public class loginInterceptor implements HandlerInterceptor {
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 若session有值,則放行
        HttpSession session = request.getSession();
        if (session.getAttribute("USERNAME")!=null){
            return true;
        }
        // 若是登入頁面,則放行
        System.out.println(request.getRequestURI());
        if(request.getRequestURI().contains("new")){
            return true;
        }
        // 否則 跳轉到登入頁面
        request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request, response);
        return false;
    }
}
           
  • 配置攔截器
<!--配置攔截器-->
    <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/**"/>
            <bean class="zy.interceptor.loginInterceptor"/>
        </mvc:interceptor>
    </mvc:interceptors>