目的:將返回 的body中的數(shù)據(jù)進行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);
// 獲取緩存的響應數(shù)據(jù)
byte[] bytes = mResp.getBytes();
String backMsg = new String(bytes, "UTF-8");
String encode = URLEncoder.encode(backMsg, "UTF-8");
byte[] bts = encode.getBytes();
// 將編碼數(shù)據(jù)響應給客戶端
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;
}
/**
* // 將數(shù)據(jù)寫到 byte 中
*
* @return
* @throws IOException
*/
@Override
public ServletOutputStream getOutputStream() throws IOException {
return new MyServletOutputStream(bytes);
}
/**
* 重寫父類的 getWriter() 方法兵多,將響應數(shù)據(jù)緩存在 PrintWriter 中
*/
@Override
public PrintWriter getWriter() throws IOException {
try {
pwrite = new PrintWriter(new OutputStreamWriter(bytes, "utf-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return pwrite;
}
/**
* 獲取緩存在 PrintWriter 中的響應數(shù)據(jù)
*
* @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();
}
}