SpringBoot攔截器中使用RedisTemplate


SpringBoot攔截器中使用RedisTemplate

最近在做項目的過程中需要在攔截器中注入RedisTemplate對象,結果發現一只空指針。

攔截器代碼如下:

package com.moti.component;

import org.springframework.web.servlet.HandlerInterceptor;

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

/**
 * @Description 登錄攔截器:用於登錄檢查,權限控制
 * @Author xw
 * @Date 15:09 2020/2/26
 * @Param  * @param null
 * @return
 **/
public class LoginHandlerInterceptor implements HandlerInterceptor {

  	@Autowired
    private RedisTemplate redisTemplate;
  
    /**
     * 在目標方式執行之前執行
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Object loginUser = request.getSession().getAttribute("loginUser");
        if (loginUser==null){
            //未登錄,返回登錄頁面
            response.sendRedirect("/u-cloud/");
            return false;
        }else {
            //已登錄,放行
            return true;
        }
    }
}

仔細一想,攔截器在SpringContext初始化之前就執行了,Bean初始化之前它就執行了,所以它肯定是無法獲取SpringIOC容器中的內容的。那么我們就讓攔截器執行的時候實例化攔截器Bean,在攔截器配置類里面先實例化攔截器,然后再獲取就能解決這個問題啦。

package com.moti.config;

import com.moti.component.LoginHandlerInterceptor;
import org.springframework.boot.web.server.ErrorPage;
import org.springframework.boot.web.server.ErrorPageRegistrar;
import org.springframework.boot.web.server.ErrorPageRegistry;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.util.unit.DataSize;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.MultipartConfigElement;

@Configuration
public class MvcConfig implements WebMvcConfigurer, ErrorPageRegistrar {
    @Bean
    public MultipartConfigElement multipartConfigElement() {
        MultipartConfigFactory factory = new MultipartConfigFactory();
        //文件最大
        factory.setMaxFileSize(DataSize.parse("1024000KB"));
        /// 設置總上傳數據總大小
        factory.setMaxRequestSize(DataSize.parse("1024000KB"));
        return factory.createMultipartConfig();
    }

    /**
     * @Description 注冊視圖控制器
     * @Author xw
     * @Date 15:11 2020/2/26
     * @Param [registry]
     * @return void
     **/
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("index");
        registry.addViewController("/temp-file").setViewName("temp-file");
        registry.addViewController("/error400Page").setViewName("error/400");
        registry.addViewController("/error401Page").setViewName("error/401");
        registry.addViewController("/error404Page").setViewName("error/404");
        registry.addViewController("/error500Page").setViewName("error/500");
    }

    /**
     * 提前new出 防止redis失效
     * @return
     */
    @Bean
    public LoginHandlerInterceptor getLoginHandlerInterceptor(){
        return new LoginHandlerInterceptor();
    }

    /**
     * @Description  注冊登錄攔截器 addPathPatterns() -> 攔截的請求  excludePathPatterns -> 不攔截的請求
     * @Author xw
     * @Date 15:10 2020/2/26
     * @Param [registry]
     * @return void
     **/
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(getLoginHandlerInterceptor()).addPathPatterns("/**")
                .excludePathPatterns(
                        "/","/temp-file","/error400Page","/error401Page","/error404Page","/error500Page","/uploadTempFile","/admin","/sendCode","/loginByQQ","/login","/register","/file/share","/connection",
                        "/asserts/**","/**/*.css", "/**/*.js", "/**/*.png ", "/**/*.jpg"
                        ,"/**/*.jpeg","/**/*.gif", "/**/fonts/*", "/**/*.svg");
    }
    
    /**
     * @Description 配置錯誤頁面
     * @Author xw
     * @Date 13:27 2020/3/11
     * @Param [registry]
     * @return void
     **/
    @Override
    public void registerErrorPages(ErrorPageRegistry registry) {
        ErrorPage error400Page = new ErrorPage(HttpStatus.BAD_REQUEST, "/error400Page");
        ErrorPage error401Page = new ErrorPage(HttpStatus.UNAUTHORIZED, "/error401Page");
        ErrorPage error404Page = new ErrorPage(HttpStatus.NOT_FOUND, "/error404Page");
        ErrorPage error500Page = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/error500Page");
        registry.addErrorPages(error400Page,error401Page,error404Page,error500Page);
    }
}

最主要的就是加入這段代碼,並且添加攔截器的時候使用這個方法 而不是new攔截器

    /**
     * 提前new出 防止redis失效
     * @return
     */
    @Bean
    public LoginHandlerInterceptor getLoginHandlerInterceptor(){
        return new LoginHandlerInterceptor();
    }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM