(入門SpringBoot)SpringBoot結合攔截器(七)

SpringBoot攔截器:spring

  1. 攔截器仍是照舊和springmvc同樣:

@Component
public class MyInterceptor implements HandlerInterceptor {
    /**
     * preHandle:在業務處理器處理請求以前被調用。預處理,能夠進行編碼、安全控制、權限校驗等處理;
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        System.out.println("preHandle");
        //進行邏輯判斷,若是ok就返回true,不行就返回false,返回false就不會處理改請求
        return true;
    }

    /**
     * postHandle:在業務處理器處理請求執行完成後,生成視圖以前執行。後處理(調用了Service並返回ModelAndView,但未進行頁面渲染),有機會修改ModelAndView;
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle...");
    }

    /**
     * afterCompletion:在DispatcherServlet徹底處理完請求後被調用,可用於清理資源等。返回處理(已經渲染了頁面);
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion...");
    }
}安全

  1. 把攔截器放在實現了WebMvcConfigurer Java類中:


/**
 * 使用WebMvcConfigurer能夠來擴展SpringMVC的功能
 *
 * 在spring5.0以前能夠繼承WebMvcConfigurerAdapter此適配器進行配置,但spring5.0之後此適配器就被廢棄(已被標註爲@Deprecated),
 * 目前有兩種解決方案,一種是直接實現WebMvcConfigurer,另外一種是直接繼承WebMvcConfigurationSupport,官方推薦第一種方案。
 */
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    /**
     * 自定義攔截規則
     *
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // addPathPatterns - 用於添加攔截規則
        // excludePathPatterns - 用戶排除攔截
        registry.addInterceptor(new MyInterceptor())
                .addPathPatterns("/**")
                .excludePathPatterns("/");
    }
}mvc

相關文章
相關標籤/搜索