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

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

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

如何配置攔截器

step1: 自定義攔截器

/**
 * 自定義攔截器
 */
public class MyInterceptor implements HandlerInterceptor {
    private static final Logger logger = LoggerFactory.getLogger(MyInterceptor.class);
    /**
     * 在請求匹配controller之前執(zhí)行,返回true才行進(jìn)行下一步
     * @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了,但是還沒有進(jìn)入視圖渲染
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }
    /**
     * 視圖也渲染完了,此時(shí)我可以做一些清理工作了
     * @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類時(shí),會(huì)導(dǎo)致resources/static下的靜態(tài)資源也被攔截,如果我們不想靜態(tài)資源被攔截,可以嘗試以下兩種方法。

/**
* 在MyInterceptorConfig中重寫addResourceHandlers方法,重新指定靜態(tài)資源
* 推薦在前后端分離時(shí)使用,后臺(tái)不需要訪問靜態(tài)資源
*
* @param registry
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
   registry.addResourceHandler("/**").addResourceLocations(
           "classpath:/static/");
   super.addResourceHandlers(registry);
}
/**
 * 將MyInterceptorConfig類由繼承WebMvcConfigurationSupport改為實(shí)現(xiàn)WebMvcConfigurer
 * 推薦在非前后端分離時(shí)使用,后臺(tái)需要訪問靜態(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:自定義注解

/**
 * 自定義注解用來指定某個(gè)方法不用攔截
 */
@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才會(huì)執(zhí)行方法,返回false不會(huì)執(zhí)行
    return false;
}

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

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

實(shí)例-登錄驗(yàn)證

用攔截器實(shí)現(xiàn)一個(gè)登錄驗(yà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();
        // 判斷用戶有沒有登錄,一般登錄之后的用戶都有一個(gè)對應(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才會(huì)執(zhí)行方法,返回false不會(huì)執(zhí)行
        return true;
    }
    /**
     * 已經(jīng)執(zhí)行完controller了,但是還沒有進(jìn)入視圖渲染
     * @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í)行完{}了,但是還沒有進(jìn)入視圖渲染", methodName);
    }
    /**
     * 視圖也渲染完了,此時(shí)我可以做一些清理工作了
     * @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("視圖也渲染完了,此時(shí)我可以做一些清理工作了");
    }
}

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)容會(huì)失效。 需要重新指定靜態(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:測試

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

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

相關(guān)文章

  • SpringBoot后端接收參數(shù)優(yōu)化代碼示例(統(tǒng)一處理前端參數(shù))

    SpringBoot后端接收參數(shù)優(yōu)化代碼示例(統(tǒng)一處理前端參數(shù))

    使用Spring Boot開發(fā)API的時(shí)候,讀取請求參數(shù)是服務(wù)端編碼中最基本的一項(xiàng)操作,下面這篇文章主要給大家介紹了關(guān)于SpringBoot后端接收參數(shù)優(yōu)化(統(tǒng)一處理前端參數(shù))的相關(guān)資料,需要的朋友可以參考下
    2024-07-07
  • SpringBoot開啟Swagger并配置基本信息方式

    SpringBoot開啟Swagger并配置基本信息方式

    這篇文章主要介紹了SpringBoot開啟Swagger并配置基本信息方式,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2024-05-05
  • 如何解決EasyExcel導(dǎo)出文件LocalDateTime報(bào)錯(cuò)問題

    如何解決EasyExcel導(dǎo)出文件LocalDateTime報(bào)錯(cuò)問題

    這篇文章主要介紹了如何解決EasyExcel導(dǎo)出文件LocalDateTime報(bào)錯(cuò)問題,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-06-06
  • Java實(shí)現(xiàn)文件名倒序排序的技術(shù)指南

    Java實(shí)現(xiàn)文件名倒序排序的技術(shù)指南

    在實(shí)際開發(fā)過程中,我們經(jīng)常需要對文件進(jìn)行操作和處理,一個(gè)常見的需求是按文件名倒序排列文件列表,以便于文件的管理和查找,本文將介紹如何在Java中實(shí)現(xiàn)文件名倒序排序,并提供詳細(xì)的代碼案例,需要的朋友可以參考下
    2024-08-08
  • 一行java代碼實(shí)現(xiàn)高斯模糊效果

    一行java代碼實(shí)現(xiàn)高斯模糊效果

    這篇文章主要為大家詳細(xì)介紹了一行java代碼實(shí)現(xiàn)高斯模糊效果,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2017-07-07
  • JAVA構(gòu)造方法/構(gòu)造器以及this使用方式

    JAVA構(gòu)造方法/構(gòu)造器以及this使用方式

    這篇文章主要介紹了JAVA構(gòu)造方法/構(gòu)造器以及this使用方式,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2024-03-03
  • SpringBoot?@DS注解實(shí)現(xiàn)多數(shù)據(jù)源配置以及問題解決辦法

    SpringBoot?@DS注解實(shí)現(xiàn)多數(shù)據(jù)源配置以及問題解決辦法

    這篇文章主要給大家介紹了關(guān)于SpringBoot?@DS注解實(shí)現(xiàn)多數(shù)據(jù)源配置以及問題解決辦法,所謂多數(shù)據(jù)源就是一個(gè)Java EE項(xiàng)目中采用了不同數(shù)據(jù)庫實(shí)例中的多個(gè)庫,或者是同一個(gè)數(shù)據(jù)庫實(shí)例中的多個(gè)不同庫,需要的朋友可以參考下
    2023-11-11
  • Spring-AOP 靜態(tài)普通方法名匹配切面操作

    Spring-AOP 靜態(tài)普通方法名匹配切面操作

    這篇文章主要介紹了Spring-AOP 靜態(tài)普通方法名匹配切面操作,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-07-07
  • Springboot整合Redis最簡單例子分享

    Springboot整合Redis最簡單例子分享

    這篇文章主要介紹了Springboot整合Redis最簡單例子分享,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-10-10
  • SpringMVC?RESTFul實(shí)戰(zhàn)案例訪問首頁

    SpringMVC?RESTFul實(shí)戰(zhàn)案例訪問首頁

    這篇文章主要為大家介紹了SpringMVC?RESTFul實(shí)戰(zhàn)案例訪問首頁,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-05-05

最新評論