欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

SpringBoot配置攔截器實現(xiàn)過程詳解

 更新時間:2022年10月21日 16:33:04   作者:大司空°  
在系統(tǒng)中經(jīng)常需要在處理用戶請求之前和之后執(zhí)行一些行為,例如檢測用戶的權(quán)限,或者將請求的信息記錄到日志中,即平時所說的"權(quán)限檢測"及"日志記錄",下面這篇文章主要給大家介紹了關(guān)于在SpringBoot項目中整合攔截器的相關(guān)資料,需要的朋友可以參考下

如何配置攔截器

step1: 自定義攔截器

/**
 * 自定義攔截器
 */
public class MyInterceptor implements HandlerInterceptor {
    private static final Logger logger = LoggerFactory.getLogger(MyInterceptor.class);
    /**
     * 在請求匹配controller之前執(zhí)行,返回true才行進行下一步
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        return false;
    }
    /**
     * 已經(jīng)執(zhí)行完controller了,但是還沒有進入視圖渲染
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }
    /**
     * 視圖也渲染完了,此時我可以做一些清理工作了
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}

step2:配置攔截器

@Configuration
public class MyInterceptorConfig extends WebMvcConfigurationSupport {
    @Override
    protected void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new MyInterceptor()).addPathPatterns("/**"); // 攔截所有內(nèi)容:/** 攔截部分內(nèi)容:/admin/**
        super.addInterceptors(registry);
    }
}

攔截器設(shè)置容易出現(xiàn)的問題

靜態(tài)資源被攔截

MyInterceptorConfig 繼承 WebMvcConfigurationSupport類時,會導(dǎo)致resources/static下的靜態(tài)資源也被攔截,如果我們不想靜態(tài)資源被攔截,可以嘗試以下兩種方法。

/**
* 在MyInterceptorConfig中重寫addResourceHandlers方法,重新指定靜態(tài)資源
* 推薦在前后端分離時使用,后臺不需要訪問靜態(tài)資源
*
* @param registry
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
   registry.addResourceHandler("/**").addResourceLocations(
           "classpath:/static/");
   super.addResourceHandlers(registry);
}
/**
 * 將MyInterceptorConfig類由繼承WebMvcConfigurationSupport改為實現(xiàn)WebMvcConfigurer
 * 推薦在非前后端分離時使用,后臺需要訪問靜態(tài)資源
 *
 */
@Configuration
public class MyInterceptorConfig implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new MyInterceptor()).addPathPatterns("/**"); // 攔截所有內(nèi)容:/** 攔截部分內(nèi)容:/admin/**
    }
}

如何取消攔截操作

step1:自定義注解

/**
 * 自定義注解用來指定某個方法不用攔截
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface UnInterception {
}

step2:修改攔截器MyInterceptor中的preHandle方法

/**
 * 在請求匹配controller之前執(zhí)行
 * @param request
 * @param response
 * @param handler
 * @return
 * @throws Exception
 */
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    
    UnInterception unInterception = method.getAnnotation(UnInterception.class);
    if(null != unInterception) {
        logger.info("不需要攔截,可以執(zhí)行");
        return true;
    }
    // 返回true才會執(zhí)行方法,返回false不會執(zhí)行
    return false;
}

step3:在不需要攔截的controller上加上UnInterception注解

@Controller
@RequestMapping("/interceptor")
public class InterceptorController {
    @UnInterception
    @RequestMapping("/test")
    public String test() {
        return "hello";
    }
}

實例-登錄驗證

用攔截器實現(xiàn)一個登錄驗證功能

step1:自定義攔截器

import com.kimmel.course13.annotation.UnInterception;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
/**
 * 自定義攔截器
 */
public class MyInterceptor implements HandlerInterceptor {
    private static final Logger logger = LoggerFactory.getLogger(MyInterceptor.class);
    /**
     * 在請求匹配controller之前執(zhí)行
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        String methodName = method.getName();
        // 判斷用戶有沒有登錄,一般登錄之后的用戶都有一個對應(yīng)的token
        UnInterception unInterception = method.getAnnotation(UnInterception.class);
        String token = request.getParameter("token");
        if (null == token || "".equals(token)) {
            logger.info("用戶未登錄,沒有權(quán)限執(zhí)行{}請登錄", methodName);
            return false;
        }
        // 返回true才會執(zhí)行方法,返回false不會執(zhí)行
        return true;
    }
    /**
     * 已經(jīng)執(zhí)行完controller了,但是還沒有進入視圖渲染
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        String methodName = method.getName();
        logger.info("已經(jīng)執(zhí)行完{}了,但是還沒有進入視圖渲染", methodName);
    }
    /**
     * 視圖也渲染完了,此時我可以做一些清理工作了
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        logger.info("視圖也渲染完了,此時我可以做一些清理工作了");
    }
}

step2:配置攔截器

import com.kimmel.course13.Interceptor.MyInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
@Configuration
public class MyInterceptorConfig extends WebMvcConfigurationSupport {
    @Override
    protected void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new MyInterceptor()).addPathPatterns("/**"); // 攔截所有內(nèi)容:/** 攔截部分內(nèi)容:/admin/**
        super.addInterceptors(registry);
    }
    /**
     * 發(fā)現(xiàn)如果繼承了WebMvcConfigurationSupport,則在yml中配置的相關(guān)內(nèi)容會失效。 需要重新指定靜態(tài)資源
     *
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**").addResourceLocations(
                "classpath:/static/");
        registry.addResourceHandler("swagger-ui.html").addResourceLocations(
                "classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations(
                "classpath:/META-INF/resources/webjars/");
        super.addResourceHandlers(registry);
    }
}

step3:自定義測試controller

@Controller
@RequestMapping("/interceptor")
public class InterceptorController {
    @RequestMapping("/test")
    public String test() {
        return "hello";
    }
}

step4:測試

進入瀏覽器,輸入http://localhost:8080/interceptor/test
結(jié)果:無法進入,日志:用戶未登錄,沒有權(quán)限執(zhí)行 test 請登錄
進入瀏覽器,輸入http://localhost:8080/interceptor/test?token=1
結(jié)果:成功進入hello.html

到此這篇關(guān)于SpringBoot配置攔截器實現(xiàn)過程詳解的文章就介紹到這了,更多相關(guān)SpringBoot配置攔截器內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論