JavaWeb-用过滤器修改请求的返回状态码
Posted yaohuimo
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JavaWeb-用过滤器修改请求的返回状态码相关的知识,希望对你有一定的参考价值。
问题: 客户SDK对接服务,默认只识别200和非200的请求状态码。需要修改当前应用的状态码(如将201转为200)
解决方案:通过扩展HttpServletResponseWrapper,获取到每个请求的状态码,满足条件的做修改即可
具体代码:
package com.supermap.huawei; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponseWrapper; /** * 1、输出http信息 2、修改返回的状态码 * */ public class ResponseCodeFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; StatusExposingServletResponse response = new StatusExposingServletResponse( (HttpServletResponse) res); String ip = request.getRemoteAddr(); String method = request.getMethod(); String url = request.getRequestURI(); String characterEncoding = request.getCharacterEncoding(); String referer = request.getHeader("Referer"); chain.doFilter(request, response); int status = response.getStatus(); System.out.println(ip + method + characterEncoding + referer + url + status); // String s1 = "" + status; if (status == 201) { // if(s1.contains("20")){ response.setStatus(200); } else { response.setStatus(status); } } @Override public void destroy() { } public static class StatusExposingServletResponse extends HttpServletResponseWrapper implements HttpServletResponse { private int status = 200; public StatusExposingServletResponse(HttpServletResponse response) { super(response); } @Override public void setStatus(int sc) { this.status = sc; super.setStatus(sc); } public int getStatus() { return status; } } }
web.xml中的配置
<filter> <filter-name>ResponseCodeFilter</filter-name> <filter-class>com.supermap.test.ResponseCodeFilter</filter-class> </filter> <filter-mapping> <filter-name>ResponseCodeFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
修改前:
修改后
以上是关于JavaWeb-用过滤器修改请求的返回状态码的主要内容,如果未能解决你的问题,请参考以下文章