springboot 攔截器解決authorization為null
阿新 • • 發佈:2021-10-21
本專案為前後端分離,介面採用springboot2+mybatis方式,前端header攜帶authorization引數請求介面,有些介面不需要攜帶authorization,本人初搞java,在研究了老半天后如下的方式解決了我的問題,在攔截器裡拿到了我要的authorization,相關配置程式碼如下:
一、建立攔截器配置
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
一開始拿不到authorization是因為在攔截器配置裡 少了下面這段話,最初是registry.addInterceptor(new new AuthorizationInterceptor())這種寫法,怎麼都拿不到authorization;
//讓bean提前載入 @Bean public HandlerInterceptor getInterceptor(){ return new AuthorizationInterceptor(); } @Override public void addInterceptors(InterceptorRegistry registry) { //註冊攔截器 InterceptorRegistration registration = registry.addInterceptor(getInterceptor()); registration.addPathPatterns("/**"); registration.excludePathPatterns( "/api/Base_User/UserLogin", "/api/Base_User/GetCode", "/api/Base_PT_Type/GetDataList", "/api/Base_User/UserInfoByToken", "/**/*.html", "/**/*.js", "/**/*.css", "/**/*.woff", "/**/*.ttf" ); } }
二、攔截器
public class AuthorizationInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { if (HttpMethod.OPTIONS.toString().equals(request.getMethod())){ response.setStatus(HttpServletResponse.SC_OK); return true; } String authorization = request.getHeader("authorization"); if (StringHelper.isEmpty(authorization)){ return false; } String userid= TokenUtils.verify(authorization.replace("Bearer ","")); if (StringHelper.isEmpty(userid)){ ResponseModel dataobj=new ResponseModel(0,false,"token無效"); return false; } return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception { }
}