SpringBoot攔截器使用

單位要做用戶權限校驗,使用token進行校驗和單點登錄,這是當時做的一個demo

攔截器配置類
實現WebConfigurer,增加@Configuration註解。老版本是要繼承Adapter,現在都用實現接口的方式了。
配置類將攔截器註冊進去,然後配置攔截規則。

@Configuration
public class InterceptorConfig implements WebMvcConfigurer {

    @Autowired
    private MyInterceptor myInterceptor;

    //註冊攔截器
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        InterceptorRegistration interceptorRegistration = registry.addInterceptor(myInterceptor);//註冊攔截前端所有請求
        interceptorRegistration.addPathPatterns("/**");//攔截前端所有請求
        interceptorRegistration.excludePathPatterns("/user/login");//不攔截前端的請求
    }

}

攔截器類
攔截器類實現HandlerInterceptor類
preHandle方法在請求處理之前進行調用(Controller方法調用之前)
postHandle請求處理之後進行調用,但是在視圖被渲染之前(Controller方法調用之後)
afterCompletion在整個請求結束之後被調用,也就是在DispatcherServlet 渲染了對應的視圖之後執行(主要是用於進行資源清理工作)

/**
 * 攔截器類
 */
@Component
public class MyInterceptor implements HandlerInterceptor {

    //日誌
    private static Logger logger = LoggerFactory.getLogger(MyInterceptor.class);

    //單點服務url
    @Value("${token.tokenUrl}")
    private String url;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        try {
            logger.info("************************************進入攔截器**********************************");
            //從前端請求中獲取token 權限id 節點id
            String token = request.getHeader("Authorization");
            String needPermission = request.getHeader("needPermission");
            logger.info("攔截器獲取token ===== " + token);
            //如果是用戶身份是遊客,則不需要登錄 直接放行
            if (StringUtils.isNotEmpty(needPermission)) {
                if (!Boolean.valueOf(needPermission)) {
                    return true;
                }
            }
            //如果沒有Token爲空,攔截
            if (StringUtils.isEmpty(token)) {
                logger.info("no token");
                //給前端返回信息,由前端控制路由跳轉,就不用後端做重定向到登錄頁
                AjaxResult ajaxResult = new AjaxResult();
                ajaxResult.put("code",CodeStatus.noAuthorization);
                ajaxResult.put("msg","no token");
                response.getOutputStream().write(JSONObject.toJSONString(ajaxResult).getBytes("utf-8"));
                response.getOutputStream().flush();
                return false;
            }
            request.setAttribute("userIdByToken", token);
            //設置header
            HttpClientUtil.setToken(token);
            HttpClientUtil.setNeedPermission(needPermission);
            //去單點登錄服務驗證token
            String doPostWithHeader = HttpClientUtil.doPostWithHeader(1, url, "");
            logger.debug("doPostWithHeader : " + doPostWithHeader);
            //單點登錄服務返回的內容
            AjaxResult parseObject = JSONObject.parseObject(doPostWithHeader, AjaxResult.class);
            int code = (int) parseObject.get("code");
            if (CodeStatus.tokenCorrect == code) {//正確
                logger.info("token check right and not timeout");
                return true;
            } else {
                response.getOutputStream().write(JSONObject.toJSONString(parseObject).getBytes("utf-8"));
                response.getOutputStream().flush();
                return false;
            }
        } catch (Exception e) {
            logger.error("exception : ", e);
            response.getOutputStream().write(JSONObject.toJSONString(e).getBytes("utf-8"));
            response.getOutputStream().flush();
            return false;
        }
    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle執行了。。。。。。。");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion執行了。。。。。。。");
    }


}

Controller類

@RestController
public class EmptyController {

    //這個接口是爲了讓用戶進攔截器,去得到單點登錄服務返回的不同的code值
    @GetMapping("/goToInterceptor")
    public AjaxResult A(){
        AjaxResult ajaxResult = new AjaxResult();
        ajaxResult.put("code",0);
        ajaxResult.put("msg","token check right and not timeout");
        return ajaxResult;
    }

}

啓動類

/**
 * 啓動程序
 *
 */
@SpringBootApplication(exclude={DataSourceAutoConfiguration.class})
@EnableScheduling
@MapperScan("cn.com.taiji.*.mapper")
@ComponentScan({"cn.com.taiji.*.*"})
public class TaiPortalApplication {
    public static void main(String[] args) {
        SpringApplication.run(TaiPortalApplication.class, args);
        System.out.println("===================啓動成功======================");
    }
    
}

資源攔截器
ViewControllerRegistry能設置頁面跳轉,不用進Controller,攔截到指定的地址,然後跳到指定頁面,比如跳首頁,跳錯誤頁之類的。

/**
 * 通用配置
 */
@Configuration
public class ResourcesConfig implements WebMvcConfigurer {
    /**
     * 首頁地址
     */
    @Value("${taiji.indexUrl}")
    private String indexUrl;

    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }

    /**
     * 默認首頁的設置,當輸入域名是可以自動跳轉到默認指定的網頁
     */
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("forward:" + indexUrl);
    }

    /**
     * 靜態資源文件映射配置
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        /** 文件上傳路徑 */
        registry.addResourceHandler("/profile/**").addResourceLocations("file:" + Global.getProfile());
        // 注意 :
        // 1. addResourceHandler 參數可以有多個
        // 2. addResourceLocations 參數可以是多個,可以混合使用 file: 和 classpath : 資源路徑
        // 3. addResourceLocations 參數中資源路徑必須使用 / 結尾,如果沒有此結尾則訪問不到

        // 映射到文件系統中的靜態文件(應用運行時,這些文件無業務邏輯,但可能被替換或者修改)
        registry.addResourceHandler("/repo/**").addResourceLocations("file:/tmp/");

        // 映射到jar包內的靜態文件(真正的靜態文件,應用運行時,這些文件無業務邏輯,也不能被替換或者修改)
        registry.addResourceHandler("/my-static/**").addResourceLocations("classpath:/my-static/");
    }

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章