标签: 杂谈 |
1.先实现一个对Response的包装器:
- public
class StatusExposingServletRes ponse extends HttpServletResponseWrapp er { -
-
private int httpStatus; -
-
public StatusExposingServletRes ponse(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; -
} -
- }
- public
class StatusReportingFilter implements Filter { -
-
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { -
StatusExposingServletRes ponse response = new StatusExposingServletRes ponse((HttpServletResponse)res); -
chain.doFilter(req, response); -
int status = response.getStatus(); -
// report -
} -
-
public void init(FilterConfig config) throws ServletException { -
//empty -
} -
-
public void destroy() { -
// empty -
} -
- }
本文介绍了一种通过自定义过滤器和响应包装器的方法来捕获HTTP响应状态的技术。该技术通过创建一个实现了HttpServletResponse接口的包装类,并在过滤器中使用这个包装类来替换原始的响应对象,从而使得开发者能够轻松地获取到HTTP响应的状态码。

3099

被折叠的 条评论
为什么被折叠?



