spring boot 拦截器不拦截静态资源,只拦截controller的方法

2023-02-10 11:48:25

拦截器拦截静态资源问题

实现拦截器的做法就是实现HandlerInterceptor
然后再WebMvcConfigurer里配置拦截器

这个时候,一般要手动添加过滤的静态资源路径,如果静态资源路径修改,则拦截器要修改

如果有添加其他拦截/**的拦截器,也需要配置静过滤态资源路径

@Configuration
public class WebConfigurer implements WebMvcConfigurer {

    @Autowired
    private LoginInterceptor loginInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        String []strs = {"/static/**","/project/**","/assets/**","/login","/login.do"};
        registry.addInterceptor(loginInterceptor).excludePathPatterns(strs);
    }

}

只拦截controller方法

利用HandlerInterceptor 接口的handler
如果是controller的方法,handler为 HandlerMethod
如果是资源类,handler为 org.springframework.web.servlet.resource.ResourceHttpRequestHandler

public interface HandlerInterceptor {
    default boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        return true;
    }
	...

实现

加一层抽象类,新增的拦截器继承该抽象类,并在controllerMethodPreHandle方法实现业务功能,即可忽视静态资源类

public abstract class AbstrctControllerInterceptor implements HandlerInterceptor {

    protected abstract boolean controllerMethodPreHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException;

    @Override
    public final boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //如果是controller的方法handler为HandlerMethod
        //如果是资源类则handler为org.springframework.web.servlet.resource.ResourceHttpRequestHandler
        if(handler instanceof HandlerMethod){
            return controllerMethodPreHandle(request,response,handler);
        }
        //否则不拦截
        return true;
    }
}

登录拦截器实现

@Component
public class LoginInterceptor extends AbstrctControllerInterceptor {

    @Override
    protected boolean controllerMethodPreHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        Object user = request.getSession().getAttribute(ConstantValue.USER_CONTEXT_KEY);
        if(user == null){
            response.sendRedirect("/login");
            return false;
        }
        return true;
    }
}

对比之前的配置,可以忽视资源路径了

@Configuration
public class WebConfigurer implements WebMvcConfigurer {

    @Autowired
    private LoginInterceptor loginInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
//        String []strs = {"/static/**","/project/**","/assets/**","/login","/login.do"};
        String []strs = {"/login","/login.do"};
        registry.addInterceptor(loginInterceptor).excludePathPatterns(strs);
    }

}
  • 作者:cying2029
  • 原文链接:https://blog.csdn.net/qq_41653935/article/details/126855222
    更新时间:2023-02-10 11:48:25