目的:将返回 的body中的数据进行url编码后 再进行返回
ResponseBodyFilter
@WebFilter(filterName = "responseBodyFilter",
urlPatterns = {
"/order/orderCancel"
})
public class ResponseBodyFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletResponse resp = (HttpServletResponse) servletResponse;
MyResponseWrapper mResp = new MyResponseWrapper(resp);
//使用复写后的wrapper
filterChain.doFilter(servletRequest, mResp);
// 获取缓存的响应数据
byte[] bytes = mResp.getBytes();
String backMsg = new String(bytes, "UTF-8");
String encode = URLEncoder.encode(backMsg, "UTF-8");
byte[] bts = encode.getBytes();
// 将编码数据响应给客户端
resp.getOutputStream().write(bts);
}
@Override
public void destroy() {
}
}
MyResponseWrapper
public class MyResponseWrapper extends HttpServletResponseWrapper {
private static final Logger logger = LoggerFactory.getLogger(MyResponseWrapper.class);
private ByteArrayOutputStream bytes = new ByteArrayOutputStream();
private HttpServletResponse response;
private PrintWriter pwrite;
public MyResponseWrapper(HttpServletResponse response) {
super(response);
this.response = response;
}
/**
* // 将数据写到 byte 中
*
* @return
* @throws IOException
*/
@Override
public ServletOutputStream getOutputStream() throws IOException {
return new MyServletOutputStream(bytes);
}
/**
* 重写父类的 getWriter() 方法,将响应数据缓存在 PrintWriter 中
*/
@Override
public PrintWriter getWriter() throws IOException {
try {
pwrite = new PrintWriter(new OutputStreamWriter(bytes, "utf-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return pwrite;
}
/**
* 获取缓存在 PrintWriter 中的响应数据
*
* @return
*/
public byte[] getBytes() {
if (null != pwrite) {
pwrite.close();
return bytes.toByteArray();
}
if (null != bytes) {
try {
bytes.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
return bytes.toByteArray();
}
}
网友评论