ServletResponse 和 HttpServletResponseWrapper 之间的区别?

发布于 2024-11-28 19:19:16 字数 1782 浏览 0 评论 0原文

我是 servlet 新手,正在阅读一些有关过滤器和包装器的文本。我可以理解过滤器,但对包装器感到困惑。在书中,作者给出了一个例子:

如果没有包装器:

public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain)
            throws IOException, ServletException {

        String name = request.getParameter("name").trim();

        try {
            chain.doFilter(request, response);
            PrintWriter out = response.getWriter();
            if (name.length() == 0) {
                out.println("Some message");
                out.println("</body>");
                out.println("</html>");
                out.close();
            }
        } catch (Throwable t) {
        }
    }

如果有包装器:

 public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain)
            throws IOException, ServletException {

        String name = request.getParameter("name").trim();

        HttpServletResponse httpRes = (HttpServletResponse) response;
        HttpServletResponseWrapper resWrapper = new HttpServletResponseWrapper(httpRes);
        try {
            chain.doFilter(request, response);

            PrintWriter out = resWrapper.getWriter(); // why dont we just use response.getWriter();
            if (name.length() == 0) {
                out.println("<h3>Some message");
                out.println("</body>");
                out.println("</html>");
                out.close();
            }
        } catch (Throwable t) {
        }
    }

为什么我们需要 HttpServletResponseWrapper 而在情况 1 中我们可以使用 ServletResponse 做同样的事情?谁能给我一个明确的例子,说明我们必须使用 HttpServletResponseWrapper 而不是 ServletResponse?我尝试过谷歌搜索,但没有找到运气。

I am new to servlet and reading some text about filters and wrappers. I can understand filters but got confused about wrappers. In the book, the author gives an example:

In case no wrapper:

public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain)
            throws IOException, ServletException {

        String name = request.getParameter("name").trim();

        try {
            chain.doFilter(request, response);
            PrintWriter out = response.getWriter();
            if (name.length() == 0) {
                out.println("Some message");
                out.println("</body>");
                out.println("</html>");
                out.close();
            }
        } catch (Throwable t) {
        }
    }

In case of wrapper:

 public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain)
            throws IOException, ServletException {

        String name = request.getParameter("name").trim();

        HttpServletResponse httpRes = (HttpServletResponse) response;
        HttpServletResponseWrapper resWrapper = new HttpServletResponseWrapper(httpRes);
        try {
            chain.doFilter(request, response);

            PrintWriter out = resWrapper.getWriter(); // why dont we just use response.getWriter();
            if (name.length() == 0) {
                out.println("<h3>Some message");
                out.println("</body>");
                out.println("</html>");
                out.close();
            }
        } catch (Throwable t) {
        }
    }

Why we need HttpServletResponseWrapper while we can do the same thing with ServletResponse in case 1? Can anyone give me a clear example that we MUST use HttpServletResponseWrapper instead of ServletResponse? I have tried to google but found no luck.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

栖竹 2024-12-05 19:19:16

BalusC 的答案很好,但如果你刚刚开始,可能会有点不知所措。

简而言之: SerlvetResponse 及其扩展 HttpServletResponse 是告诉您可以调用哪些方法来完成您需要的操作的接口。在使用过滤器、Servlet 等的正常过程中,您将经常使用 HttpServletResponse 来告诉您的应用程序如何响应请求。

HttpServletResponseWrapper 是 HttpServletResponse 的一个特定实现,它为您提供了一种便捷的方法用您自己的一些逻辑包装现有的响应,而无需编写接口的全新实现。它有很多方法,所以这真的很好。作为一个简单的示例,假设您希望禁止调用 响应。刷新缓冲区()。使用 HttpServletResponseWrapper 的这段代码将执行以下操作:

class DisallowFlushResponseWrapper extends HttpServletResponseWrapper {
    public DisallowFlushResponseWrapper(HttpServletResponse response) {
        super(response);
    }

    @Override
    public void flushBuffer() {
        throw new UnsupportedOperationException("Don't call this!");
    }
}

使用此类包装器的典型方法是创建一个如下所示的过滤器:

class DisallowFlushFilter implements Filter {
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) {
        if (response instanceof HttpServletResponse) {
            HttpServletResponse newResponse =
                new DisallowFlushResponseWrapper((HttpServletResponse) response);
            chain.doFilter(request, newResponse);
        }
        ...
    }
    ...
}

请注意,我们使用我们自己的包装器实例将进入过滤器的响应包装起来。然后我们将包装器交给过滤器链中的下一个项目。因此,如果此过滤器之后调用flushBuffer(),则该过滤器之后的任何内容都会出现异常,因为它将在我们的包装器上调用它。由于其默认行为,包装器会将任何其他调用委托给包装的响应(这是真正的响应),因此除了调用该方法之外的所有内容都将正常工作。

BalusC's answer is good, but it might be a little overwhelming if you're just starting out.

Put simply: SerlvetResponse and its extension, HttpServletResponse, are interfaces telling you what methods are available to call to do the things you need. In the normal course of working with Filters, Servlets, et al., you'll use HttpServletResponse often to tell your app how to respond to requests.

HttpServletResponseWrapper is one particular implementation of HttpServletResponse which gives you a convenient way to wrap an existing response with some logic of your own without having to write a whole new implementation of the interface. It has a lot of methods, so this is really nice. As a trivial example, suppose you wanted to disallow calls to response.flushBuffer(). This code, using HttpServletResponseWrapper, will do that:

class DisallowFlushResponseWrapper extends HttpServletResponseWrapper {
    public DisallowFlushResponseWrapper(HttpServletResponse response) {
        super(response);
    }

    @Override
    public void flushBuffer() {
        throw new UnsupportedOperationException("Don't call this!");
    }
}

The typical way to use such a wrapper would be to create a filter like this:

class DisallowFlushFilter implements Filter {
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) {
        if (response instanceof HttpServletResponse) {
            HttpServletResponse newResponse =
                new DisallowFlushResponseWrapper((HttpServletResponse) response);
            chain.doFilter(request, newResponse);
        }
        ...
    }
    ...
}

Note that we wrap the response coming into the filter with an instance of our own wrapper. Then we hand the wrapper down to the next item in the filter chain. Thus anything that comes after this filter will get an exception if it calls flushBuffer() because it will be calling it on our wrapper. The wrapper, due to its default behavior, will delegate any other call to the wrapped response, which is the real one, so everything except calls to that one method will work normally.

赠我空喜 2024-12-05 19:19:16

这是一个糟糕的例子,它没有显示请求/响应包装器的真正好处。发出 HTML 应该由 JSP 完成,而不是由 Filter 完成,当然也不由 Servlet 完成。浏览我们的过滤器 wiki 页面,了解过滤器用途的一些想法。

如果您想要修改响应的行为,或者只是想要在请求-响应链中使用响应时收集有关响应的信息,那么响应包装器非常有用。每当某个 servlet 或 JSP 对响应调用某个方法时,就会发生修改后的行为。如果您在包装类中重写了它,那么将调用这个类。您可以在那里改变行为或收集信息。

在 Stackoverflow 上,您可以通过搜索 < 找到 HttpServletResponseWrapper 实现的真实示例代码>代码:“扩展HttpServletResponseWrapper”

That's a bad example which does not show the real benefit of request/response wrapper. Emitting HTML should be done by a JSP not by a Filter and for sure not by a Servlet. Go through our filters wiki page to get some ideas about what a Filter is to be used for.

A response wrapper is useful if you want to modify the response's behaviour or just want to collect information about the response while it is been used in the request-response chain. The modified behaviour takes then place whenever some servlet or JSP calls a certain method on the response. If you have overriden it in your wrapper class, then this one will be called instead. You could alter the behaviour or collect information there.

Here on Stackoverflow you can find real world examples of HttpServletResponseWrapper implementations by searching on code:"extends HttpServletResponseWrapper".

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文