我有一个Spring Boot应用程序,其REST端点定义如下
/usermanagement/v1/access/ldap
/usermanagement/v1/access/db
我创建了一个Spring Interceptor,用以下模式拦截所有传入的请求
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new RequestInterceptor()).addPathPatterns("/usermanagement/v1/**");
}
RequestInterceptor
@Component
public class RequestInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
return true;
}
@Override
public void postHandle(
HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)
throws Exception {
System.out.println("This is Post Handling the request");
}
}
此拦截器仅在客户端访问完整端点时才有效,即
/ usermanagement / V1 /访问/ LDAP
如果访问了部分端点,
/ usermanagement / V1 /接入
拦截器未被调用,404被返回给客户端。
有没有办法改变这种行为?我这样做的原因是因为我不希望公开特定的端点,而是公共端点,并对服务进行内部调用,并通过公共端点返回结果。
答案 0 :(得分:0)
您使用的是错误的方法。尝试使用afterCompletion
代替postHandle
new HandlerInterceptor() {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//This is called before handeling any request
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
//This is called after successfully handeling a request. It will not be called in case of an exception
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//This will always be called after a request, even in case of an exception
}
}
请求未定义的端点/usermanagement/v1/access
Spring将抛出异常。因此,它永远不会进入postHandle
。