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() {

    }

  • 相关阅读:
    一些技术鸡汤
    css优化
    Spring 通过maven pom文件配置初始化
    sql 编写横竖表转换
    Linux 常用命令笔记 (持续更新)
    java常用集合详解 contains
    jQuery Ajax(异步请求)
    java中"与"和"或"
    java8 中的时间和数据的变化
    mysql 根据查询结果集更新
  • 原文地址:https://www.cnblogs.com/wjlstation/p/13812165.html
Copyright © 2011-2022 走看看