码迷,mamicode.com
首页 > 编程语言 > 详细

JavaWeb-用过滤器修改请求的返回状态码

时间:2019-12-18 21:47:36      阅读:418      评论:0      收藏:0      [点我收藏+]

标签:方案   test   erer   highlight   contains   response   ext   解决方案   perm   

问题: 客户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-用过滤器修改请求的返回状态码

标签:方案   test   erer   highlight   contains   response   ext   解决方案   perm   

原文地址:https://www.cnblogs.com/yaohuimo/p/12063682.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!