spring boot 拦截器

来源:互联网 发布:编程从娃娃抓起 编辑:程序博客网 时间:2024/06/05 18:29

第一步

@Configuration
public class MyWebAppConfigurer extends WebMvcConfigurerAdapter {


@Autowired
private TokenInterceptor tokenInterceptor;

@Override
public void addInterceptors(InterceptorRegistry registry) {
        // 多个拦截器组成一个拦截器链
        // addPathPatterns 用于添加拦截规则
        // excludePathPatterns 用户排除拦截
        registry.addInterceptor(tokenInterceptor).addPathPatterns("/**").excludePathPatterns("/login");
        super.addInterceptors(registry);
    }
}

第二步

@Component

public class TokenInterceptor extends HandlerInterceptorAdapter {

@Autowired
private TokenService tokenService;

@Autowired
private ApplicationContext applicationContext;

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
//      session机制
// UMUser umUser = (UMUser)request.getSession().getAttribute("CURRENT_USER");
String token = request.getParameter("token");
if (StringUtils.isEmpty(token)) {
throw new GlobalBusinessException(GlobalResultStatus.USER_NOT_LOGIN);
}

String uid = tokenService.getUidByToken(token);
if (uid == null) {
throw new GlobalBusinessException(GlobalResultStatus.USER_LOGIN_TOKEN_INVALID);
}
applicationContext.setUid(uid);
return true;
}


}
原创粉丝点击