为成功 API 响应添加拦截器
Adding interceptor for success API response
我有一个 Spring 应用程序,我想在其中将用户操作记录到数据库 table 中。例如。如果用户调用了 POST createBook API,那么我想将此创建操作记录到 table.
我打算使用 Spring HandlerInterceptorAdapter
并覆盖 afterCompletion
方法。
我的问题:
如果API内部抛出异常,是否也会调用afterCompletion
方法?有什么办法只在没有抛出异常且响应成功时才拦截
我只想拦截一些特定的 API 集。除了检查方法内的 API 路径外,还有其他优雅的方法吗?
public class OperationInterceptor extends HandlerInterceptorAdapter {
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
Object handler, Exception ex) {
if ("/book".equals(request.getServletPath() && "POST".equals(request.getMethod())) {
//log the operation into db
}
if ("/order".equals(request.getServletPath() && "POST".equals(request.getMethod())) {
//log the operation into db
}
}
}
您可以在 afterCompletion
方法中添加这样的 if 条件。
if(ex!=null){
Stream.of(
new String[]{"/book", "POST"},
new String[]{"/order", "GET"})
.filter((p)-> Objects.equals(request.getServletPath(),p[0])&&Objects.equals(request.getMethod(),p[1]))
.findAny().ifPresent(r->{
System.out.println("//log oprations");
});
}
我有一个 Spring 应用程序,我想在其中将用户操作记录到数据库 table 中。例如。如果用户调用了 POST createBook API,那么我想将此创建操作记录到 table.
我打算使用 Spring HandlerInterceptorAdapter
并覆盖 afterCompletion
方法。
我的问题:
如果API内部抛出异常,是否也会调用
afterCompletion
方法?有什么办法只在没有抛出异常且响应成功时才拦截我只想拦截一些特定的 API 集。除了检查方法内的 API 路径外,还有其他优雅的方法吗?
public class OperationInterceptor extends HandlerInterceptorAdapter {
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
Object handler, Exception ex) {
if ("/book".equals(request.getServletPath() && "POST".equals(request.getMethod())) {
//log the operation into db
}
if ("/order".equals(request.getServletPath() && "POST".equals(request.getMethod())) {
//log the operation into db
}
}
}
您可以在 afterCompletion
方法中添加这样的 if 条件。
if(ex!=null){
Stream.of(
new String[]{"/book", "POST"},
new String[]{"/order", "GET"})
.filter((p)-> Objects.equals(request.getServletPath(),p[0])&&Objects.equals(request.getMethod(),p[1]))
.findAny().ifPresent(r->{
System.out.println("//log oprations");
});
}