Servlet中怎么获取response的statusCode
1个回答
展开全部
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 } } 一语解千愁!
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询