如何编写响应过滤器? [英] How to write response filter?

查看:171
本文介绍了如何编写响应过滤器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法只处理过滤器中的响应。

Is there a way to handle only response in a filter .

下面的代码是否正确?

  public void doFilter(request , response , chain) {
        //code to handle request 
          chain.doFilter(request, response);
        //code to handle response .
  }


推荐答案

这取决于你想要什么。通常,您的样本不正确。在 chain.doFilter 返回后,对响应做任何事都为时已晚。此时,整个响应已经发送到客户端,您的代码无法访问它。

It depends on what you want. In general, your sample is not correct though. After chain.doFilter has returned, it's too late to do anything with the response. At this point, entire response was already sent to the client and your code has no access to it.

您需要做的是包装请求和/或响应到您自己的类中,将这些包装器传递到 doFilter 方法中处理包装器中的任何处理。

What you need to do is to wrap request and/or response into your own classes, pass these wrappers into doFilter method and handle any processing in your wrappers.

为了使它更容易,servlet api中已经有包装器:参见 HttpServletRequestWrapper HttpServletResponseWrapper 类。如果要处理实际发送到客户端的输出,还需要编写自定义的OutputStream或Writer包装器,并从HttpServletResponse包装器返回这些包装。是的,很多包装:)

To make it easier, there are already wrappers available in servlet api: see HttpServletRequestWrapper and HttpServletResponseWrapper classes. If you want to process output that is actually sent to client, you also need to write custom OutputStream or Writer wrappers, and return those from your HttpServletResponse wrapper. Yeah, lot of wrapping :)

一些更简单的过滤器可以在不包装请求或响应的情况下工作:例如在调用 doFilter 之前,您已经可以访问请求标头,或者您可以在不调用 doFilter 的情况下发送自定义响应。但是如果你想处理请求体,你不能只读它,否则它将无法用于链的其余部分。在这种情况下,您需要再次使用包装技术。

Some simpler filters can work without wrapping request or response: e.g. before calling doFilter, you can already access request headers or you can send custom response without calling doFilter. But if you want to process request body, you cannot just read it, otherwise it won't be available to the rest of the chain. In this case you need to use the wrapping technique again.

这篇关于如何编写响应过滤器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆