我正在尝试报告从我的 web 应用程序返回的每个 HTTP 状态代码。但是,状态代码似乎无法通过 ServletResponse 访问,即使我将其转换为 HttpServletResponse。有没有办法在 ServletFilter 中访问这个值?
最佳答案
首先,您需要将状态代码保存在可访问的位置。最好用您的实现包装响应并将其保留在那里:
public class StatusExposingServletResponse extends HttpServletResponseWrapper {
private int httpStatus;
public StatusExposingServletResponse(HttpServletResponse response) {
super(response);
}
@Override
public void sendError(int sc) throws IOException {
httpStatus = sc;
super.sendError(sc);
}
@Override
public void sendError(int sc, String msg) throws IOException {
httpStatus = sc;
super.sendError(sc, msg);
}
@Override
public void setStatus(int sc) {
httpStatus = sc;
super.setStatus(sc);
}
public int getStatus() {
return httpStatus;
}
}
为了使用这个包装器,你需要添加一个 servlet 过滤器,你可以做你的报告:
public class StatusReportingFilter implements Filter {
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
StatusExposingServletResponse response = new StatusExposingServletResponse((HttpServletResponse)res);
chain.doFilter(req, response);
int status = response.getStatus();
// report
}
public void init(FilterConfig config) throws ServletException {
//empty
}
public void destroy() {
// empty
}
}
关于java - 如何从 ServletFilter 中的 ServletResponse 中获取 HTTP 状态代码?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/1302072/