springboot添加拦截器

Posted dongbo

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了springboot添加拦截器相关的知识,希望对你有一定的参考价值。

一,编写拦截器

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添加拦截器的主要内容,如果未能解决你的问题,请参考以下文章

SpringBoot拦截器----addInterceptors

springboot 登录拦截器

springboot添加拦截器

springboot中添加拦截器(记录)

springboot中添加拦截器(记录)

springboot 根据用户ID切换动态数据源代码实现