标签:Base 拦截器 springboot api registration null public authorization
本项目为前后端分离,接口采用springboot2+mybatis方式,前端header携带authorization参数请求接口,有些接口不需要携带authorization,本人初搞java,在研究了老半天后如下的方式解决了我的问题,在拦截器里拿到了我要的authorization,相关配置代码如下:
一、创建拦截器配置
#### 原代码如下,这种拿不到authorization:
public class InterceptorConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
//注册拦截器
## 新旧写法区别就在这里
InterceptorRegistration registration = registry.addInterceptor(new AuthorizationInterceptor());
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"
);
}
}
#### 新代码 增加getInterceptor()
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
//让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 {
}
}
标签:Base,拦截器,springboot,api,registration,null,public,authorization 来源: https://www.cnblogs.com/frank2828/p/15434294.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。