Servlet中怎么获取response的statusCode
答案:1 悬赏:30 手机版
解决时间 2021-02-15 21:48
- 提问者网友:喧嚣尘世
- 2021-02-15 04:01
Servlet中怎么获取response的statusCode
最佳答案
- 五星知识达人网友:话散在刀尖上
- 2021-02-15 04:23
HttpURLConnection.getResponseCode()可以获取,但需要new一个URL对象并重新发送请求,有性能损失。有没其他的获取statusCode的方法。
我在Oracle官网论坛上看见别人的讨论:可以通过apache的工具类org.apache.catalina.valves.RequestDumperValve来获取,但自己未找到其源码。另外也有人说对Reponse对象封装来跟踪statuCode,说的比较模糊,实现不便。
全部分奉上!
用的是JAVA的URL还是其他开源工具访问URLJava的URL 问题补充:myali88 写道网上搜索的,你试试:
1.先实现一个对Response的包装器:
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; } } 2.然后实现一个Filter来替换原始的HttpServletResponse,这样你就可以在Filter里面取到statusCode了
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 } } 一语解千愁!
我在Oracle官网论坛上看见别人的讨论:可以通过apache的工具类org.apache.catalina.valves.RequestDumperValve来获取,但自己未找到其源码。另外也有人说对Reponse对象封装来跟踪statuCode,说的比较模糊,实现不便。
全部分奉上!
用的是JAVA的URL还是其他开源工具访问URLJava的URL 问题补充:myali88 写道网上搜索的,你试试:
1.先实现一个对Response的包装器:
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; } } 2.然后实现一个Filter来替换原始的HttpServletResponse,这样你就可以在Filter里面取到statusCode了
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 } } 一语解千愁!
我要举报
如以上问答信息为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯