springboot添加拦截器

2021-03-23 01:24

阅读:448

标签:inter   hpa   jwt   cookie   vcc   str   after   san   oid   

一,编写拦截器

public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //若不是映射方法,直接通过
        if (!(handler instanceof HandlerMethod)){
            return true;
        }

        HandlerMethod handlerMethod = (HandlerMethod)handler;
        Method method = handlerMethod.getMethod();
        if (method.isAnnotationPresent(PassToken.class)){
            return true;
        }

        if (method.isAnnotationPresent(RequireToken.class)){
            String token = null;
            //String token = request.getHeader("token");
            Cookie[] cookies = request.getCookies();
            for (Cookie cookie : cookies) {
                if ("token".equals(cookie.getName())){
                    token = cookie.getValue();
                    break;
                }
            }
            if (token == null){
                throw new RuntimeException("无token信息,请重新登录");
            }

            String username = JwtUtils.getUsernameFromToken(token);
            if (username == null){
                throw new RuntimeException("token信息错误");
            }

            request.setAttribute("username", username + ",test");
            return true;
        }

        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}

二,配置拦截器

@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(tokenInterceptor())
            .addPathPatterns("/**");
    }

    @Bean
    public TokenInterceptor tokenInterceptor(){
        return new TokenInterceptor();
    }

}

 

springboot添加拦截器

标签:inter   hpa   jwt   cookie   vcc   str   after   san   oid   

原文地址:https://www.cnblogs.com/dongbo/p/13866756.html


评论


亲,登录后才可以留言!