zoukankan      html  css  js  c++  java
  • 过滤器中获取返回信息

    自定义过滤器(Filter), 获取返回值

    public class ResponseWrapper extends HttpServletResponseWrapper {

    private ByteArrayOutputStream buffer;

    private ServletOutputStream out;

    public ResponseWrapper(HttpServletResponse httpServletResponse) {
    super(httpServletResponse);
    buffer = new ByteArrayOutputStream();
    out = new WrapperOutputStream(buffer);
    }

    @Override
    public ServletOutputStream getOutputStream() throws IOException {
    return out;
    }

    @Override
    public void flushBuffer() throws IOException {
    if (out != null) {
    out.flush();
    }
    }

    public byte[] getContent() throws IOException {
    flushBuffer();
    return buffer.toByteArray();
    }

    class WrapperOutputStream extends ServletOutputStream {
    private ByteArrayOutputStream bos;

    public WrapperOutputStream(ByteArrayOutputStream bos) {
    this.bos = bos;
    }

    @Override
    public void write(int b) throws IOException {
    bos.write(b);
    }

    @Override
    public boolean isReady() {
    return false;
    }

    @Override
    public void setWriteListener(WriteListener arg0) {

    }
    }

    自定义过滤器类CustomFilter实现Filter接口;

    public class CustomFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    ResponseWrapper wrapperResponse = new ResponseWrapper((HttpServletResponse)response);
    chain.doFilter(request, wrapperResponse);
    byte[] content = wrapperResponse.getContent();
    if(content.length > 0) {
    String str = new String(content, "UTF-8");
    JsonObject fromJson = new Gson().fromJson(str, JsonObject.class);
    if(fromJson.get("status").toString().equals("200")) {
    //do something
    }
    }
    }
    @Override
    public void destroy() {

    }

  • 相关阅读:
    1230 jquery
    1221 监听事件
    1218 dom表格元素操作
    1216 DOM
    Java中对小数的向下取整,向上取整
    Mysql中 在SQL语句里进行日期格式转换
    一些常用格式化。价格、日期等 持续更新
    List对象里面根据某一字段去重
    java 后端 初始化图片像素(1980 x 1080)大小
    swagger里面测试List数据格式
  • 原文地址:https://www.cnblogs.com/wjlstation/p/13812165.html
Copyright © 2011-2022 走看看