你可以像这样使用一些想法:
@WebFilter(filterName = "ErrorPageFilter", urlPatterns = "/*")
public class ErrorPageFilter extends BaseHttpFilter {
private GlobalErrorHandler globalErrorHandler;
@Override
public void init(FilterConfig filterConfig) throws ServletException {
globalErrorHandler = BeansUtil.getBean(filterConfig.getServletContext(), GlobalErrorHandler.class);
}
@Override
protected void doHttpFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
chain.doFilter(request, new ErrorPageHttpServletResponseWrapper(request, response));
}
private class ErrorPageHttpServletResponseWrapper extends HttpServletResponseWrapper {
HttpServletRequest request;
public ErrorPageHttpServletResponseWrapper(HttpServletRequest request, HttpServletResponse response) {
super(response);
this.request = request;
}
@Override
public void sendError(int sc) throws IOException {
globalErrorHandler.handleError(sc, request, this);
}
@Override
public void sendError(int sc, String msg) throws IOException {
sendError(sc);
}
}
}
public interface GlobalErrorHandler {
void handleError(int responseCode, HttpServletRequest request, HttpServletResponse httpServletRequest) throws IOException;
void addHandler(int responseCode, String handlerDescription);
}