利用HttpServletResponseWrapper包装reponse

利用HttpServletResponseWrapper包装reponse

题记: 很多人或许用Spring的时候统一修改一下reponse信息,比较常见的就是给所有的response加一个status、code、message之类的要求,也有的想把response和request的日志打印出来,那么该如何做呢?那就耐心看看吧

一、背景介绍

  对于上述我们说到的这个需求,有很多中实现方式,比较容易想到的就是拦截器,过滤器等,这里我使用的是过滤器的方式来实现的,一是因为Spring天然就对Filter支持得比较好,二是开发方便容易。

  对于过滤器的实现方式,我这里也提供2种方式来实现,一种是复制ServletOutputStream的方式,一种是不复制ServletOutputStream的方式,两种方式各有用处,随君选择,后续我会开一篇原理的文章

  这里可能有读者疑问了,ServletOutputStream 是什么呀?我们看一下官方文档

1
2
Provides an output stream for sending binary data to the client. A ServletOutputStream object is normally retrieved via the ServletResponse.getOutputStream method.
This is an abstract class that the servlet container implements. Subclasses of this class must implement the java.io.OutputStream.write(int) method.

  文档里面写得很清楚,说提供一个输出流来向客户端发送数据,一个ServletOutputStream通常是reponse.getOutputStream()方法来得到,子类必须实现write方法。OK,说明我们最后要改的就是这个了,且要通过reponse.getOutputStream()这种方法得到。

二、不复制输出流方式(推荐,简便)

  1. 首先我们要创建一个Filter,这个Filter继承Spring的`OncePerRequestFilter

     继承这个Filter 跟继承普通的Filter主要区别就是它只会执行一次,在Servlet 3.0 之后,一个Filter可以被多个线程唤醒,这样就可能出现一些问题,所以我们这里使用这个

    参考文档:

    1
    The dispatcher type javax.servlet.DispatcherType.ASYNC introduced in Servlet 3.0 means a filter can be invoked in more than one thread over the course of a single request. Some filters only need to filter the initial thread (e.g. request wrapping) while others may need to be invoked at least once in each additional thread for example for setting up thread locals or to perform final processing at the very end.
  2. ResponseWrapperFilter 代码如下

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    @Order(Ordered.LOWEST_PRECEDENCE - 1)
    @WebFilter(urlPatterns = {"/common/*"},filterName = "responseWrapperFilter")
    public class ResponseWrapperFilter extends OncePerRequestFilter {
    private static final Logger LOGGER = LoggerFactory.getLogger(ResponseWrapperFilter.class);
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
    ResponseWrapper wrapper = new ResponseWrapper(response);
    try {
    filterChain.doFilter(request,wrapper);
    String responseStr = new String(wrapper.toByteArray(), response.getCharacterEncoding());
    Object parse = JSON.parse(responseStr);
    BaseResult<Object> baseResult = new BaseResult<>();
    baseResult.setData(parse);
    if (parse instanceof JSONObject){
    JSONObject resultObject = (JSONObject) parse;
    if (resultObject.containsKey("status")&&resultObject.containsKey("message")&&resultObject.containsKey("data")){
    baseResult = JSONObject.parseObject(resultObject.toJSONString(),new TypeReference<BaseResult<Object>>(){});
    }
    }
    LOGGER.info("response is ============{}",baseResult);
    //必须设置ContentLength
    response.setContentLength(JSON.toJSONBytes(baseResult).length);
    //根据http accept来设置,我这里为了简便直接写json了
    response.setContentType("application/json;charset=utf-8");
    response.getOutputStream().write(JSON.toJSONBytes(baseResult));
    } catch (Exception e) {
    LOGGER.error("数据包装器执行出错....{}", e);
    }
    }
    }

    我这个Filter主要作用就是给我们的Reponse加上status,把Controller里面的数据放到data字段里面去,加一个包装。

  3. ResponseWrapper类源代码如下:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    private ByteArrayOutputStream output;
    private ServletOutputStream filterOutput;
    public ResponseWrapper(HttpServletResponse response) {
    super(response);
    output = new ByteArrayOutputStream();
    }
    /**
    * 巧妙将ServletOutputStream放到公共变量,解决不能多次读写问题
    * @return
    * @throws IOException
    */
    @Override
    public ServletOutputStream getOutputStream() throws IOException {
    if (filterOutput == null) {
    filterOutput = new ServletOutputStream() {
    @Override
    public void write(int b) throws IOException {
    output.write(b);
    }
    @Override
    public boolean isReady() {
    return false;
    }
    @Override
    public void setWriteListener(WriteListener writeListener) {
    }
    };
    }
    return filterOutput;
    }
    public byte[] toByteArray() {
    return output.toByteArray();
    }
  4. BaseResult类

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    public class BaseResult<T> implements Serializable {
    private static final long serialVersionUID = 2120267584344923858L;
    private Integer status = 0;
    private String message = null;
    private T data = null;
    public BaseResult(){
    }
    public BaseResult(Integer status, String message, T data) {
    this.status = status;
    this.message = message;
    this.data = data;
    }
    public Integer getStatus() {
    return status;
    }
    public void setStatus(Integer status) {
    this.status = status;
    }
    public String getMessage() {
    return message;
    }
    public void setMessage(String message) {
    this.message = message;
    }
    public T getData() {
    return data;
    }
    public void setData(T data) {
    this.data = data;
    }
    @Override
    public String toString() {
    return "Result{" +
    "status=" + status +
    ", message='" + message + '\'' +
    ", data=" + data +
    '}';
    }
    }

  5. 这两个类与现有的Spring项目集成就可以实现将reponse修改的目的了

  6. 使用,浏览器访问:localhost:8080/common/getBaseResult 看效果

    1
    2
    3
    4
    5
    6
    7
    {
    data: {
    imgUrl: "htt://img.baidu.com/images/11.jpg",
    name: "itar"
    },
    status: 0
    }
  7. 是不是还漏了一个Controller

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    @RestController
    @RequestMapping({"/common","/never"})
    public class CommonControllerImpl{
    @RequestMapping(value = "/getBaseResult",method = RequestMethod.GET,produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody public JSONObject getBaseResult() {
    JSONObject jsonObject = new JSONObject();
    jsonObject.put("imgUrl","htt://img.baidu.com/images/11.jpg");
    jsonObject.put("name","itar");
    return jsonObject;
    }
    }

三、复制输出流方式

  1. 我们这里的复制输出流主要就是将ServletOutputStream 这个流复制一份,复制出来之后大家可以写写日志呀,做些特殊处理什么的。

  2. 主要使用的是apache提供的TeeOutputStream类将输出流复制一份出来。

  3. BranchResponseWrapper 类源代码如下

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    public class BranchResponseWrapper extends HttpServletResponseWrapper {
    /**
    * 我们的分支流
    */
    private ByteArrayOutputStream output;
    private ServletOutputStream filterOutput;
    private OutputStream bufferOutputStream;
    public BranchResponseWrapper(HttpServletResponse response) {
    super(response);
    /*try {
    bufferOutputStream = response.getOutputStream();
    } catch (IOException e) {
    e.printStackTrace();
    }*/
    output = new ByteArrayOutputStream();
    }
    /**
    * 利用TeeOutputStream复制流,解决多次读写问题
    * 用super.getOutputStream来获取源outputstream,也可以用注释的那种方式获取,传过来
    * @return
    * @throws IOException
    */
    @Override
    public ServletOutputStream getOutputStream() throws IOException {
    if (filterOutput == null) {
    filterOutput = new ServletOutputStream() {
    //替换构造方法
    //拿父类的response,初始化的时候,里面还没有数据,只有一些request信息和response信息,但是调用了创建outputStream,
    //private TeeOutputStream teeOutputStream = new TeeOutputStream(bufferOutputStream,output);
    private TeeOutputStream teeOutputStream = new TeeOutputStream(BranchResponseWrapper.super.getOutputStream(),output);
    @Override
    public boolean isReady() {
    return false;
    }
    @Override
    public void setWriteListener(WriteListener writeListener) {
    }
    @Override
    public void write(int b) throws IOException {
    teeOutputStream.write(b);
    }
    };
    }
    return filterOutput;
    }
    public byte[] toByteArray() {
    return output.toByteArray();
    }
    }
  4. BranchResponseWrapperFilter源代码如下

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    @Order(Ordered.LOWEST_PRECEDENCE - 1)
    @WebFilter(urlPatterns = {"/never/*"},filterName = "branchResponseWrapperFilter")
    public class BranchResponseWrapperFilter extends OncePerRequestFilter {
    private static final Logger LOGGER = LoggerFactory.getLogger(BranchResponseWrapperFilter.class);
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
    BranchResponseWrapper wrapper = new BranchResponseWrapper(response);
    try {
    filterChain.doFilter(request,wrapper);
    String respStr= new String(wrapper.toByteArray(), response.getCharacterEncoding());
    Object parse = JSON.parse(respStr);
    JSONObject jsonObject = new JSONObject();
    jsonObject.put("status",0);
    jsonObject.put("data",parse);
    LOGGER.info("response is ============{}",jsonObject);
    response.setContentType("application/json;charset=utf-8");
    //将buffer重置,因为我们要重新写入流进去
    response.resetBuffer();
    response.setContentLength(JSON.toJSONBytes(jsonObject).length);
    response.getOutputStream().write(JSON.toJSONBytes(jsonObject));
    } catch (Exception e) {
    LOGGER.error("数据包装器执行出错....{}", e);
    }
    }
    }
  5. 使用,浏览器访问:localhost:8080/never/getBaseResult 看效果

    1
    2
    3
    4
    5
    6
    7
    {
    data: {
    imgUrl: "htt://img.baidu.com/images/11.jpg",
    name: "itar"
    },
    status: 0
    }

四、细节

  1. 可能大家注意到了,我这里Filter都是有URLPattern的,都需要配置@WebFilter注解的,Spring Boot中这个注解要生效必须在启动类中写上 @ServletComponentScan ,单纯Spring 应用需要在Web.xml中配置filter。
  2. 第二种方式中response.resetBuffer();这句话非常重要,不然会出现FixedLengthOverflowException , 主要作用就是将buffer里面的数据清空
  3. 原理说白了就是提前通过你的Filter将ServletOutputStream输出到页面上去,只要执行了write方法,页面就有数据了,大家可以执行测试

五、代码下载

点击这里 注意切换到 duplicate_submissions 这个分支

END ,希望有所帮助

Compartir