在SpringBoot中添加拦截器忽略请求URL当中的指定字符串

1 自定义拦截器

@Component
public class GlobalInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String path = request.getRequestURI();
        if (path.contains("/api/")) {
            path = path.replaceAll("/api/", "/");
            request.getRequestDispatcher(path).forward(request, response);
        }
        return true;
    }
}

2 注册拦截器

@Configuration
@EnableWebMvc
public class WebMvcConfig implements WebMvcConfigurer {

    GlobalInterceptor globalInterceptor;

    @Autowired
    public WebMvcConfig(GlobalInterceptor globalInterceptor) {
        this.globalInterceptor = globalInterceptor;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(globalInterceptor).addPathPatterns("/api/**");
    }
}

你可能感兴趣的:(spring,boot,java,python)