码迷,mamicode.com
首页 > 编程语言 > 详细

springboot添加拦截器

时间:2020-10-24 10:26:38      阅读:28      评论:0      收藏:0      [点我收藏+]

标签: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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!