溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

SpringCloud使用HandlerInterceptor攔截器

發(fā)布時間:2020-07-05 21:48:53 來源:網絡 閱讀:2363 作者:煢煢木偶 欄目:編程語言
一、編寫自定義攔截器SignAutheInterceptor.class

preHandle:在業(yè)務處理器處理請求之前被調用。預處理,可以進行編碼、安全控制、權限校驗等處理;
postHandle:在業(yè)務處理器處理請求執(zhí)行完成后,生成視圖之前執(zhí)行。后處理(調用了Service并返回ModelAndView,但未進行頁面渲染),有機會修改ModelAndView (這個博主就基本不怎么用了);
afterCompletion:在DispatcherServlet完全處理完請求后被調用,可用于清理資源等。返回處理(已經渲染了頁面);

package com.xiaohang.socialcard.pre.intercepter;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 自定義攔截器
 */
public class SignAutheInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        /**
         * 通過HttpServletRequest和HttpServletResponse做相應數(shù)據(jù)處理
         */
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
二、配置攔截器InterceptorConfig.class

通過addPathPatterns屬性可配置需要進行攔截的請求路徑
通過excludePathPatterns屬性可配置不進行攔截的請求路徑

package com.xiaohang.socialcard.pre.intercepter;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

/**
 * 配置攔截器
 */
@Configuration
public class InterceptorConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new SignAutheInterceptor()).addPathPatterns("/api/v1/get/getToken");
        super.addInterceptors(registry);
    }
}
向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經查實,將立刻刪除涉嫌侵權內容。

AI