将ServletResponse作为参数传递的任何好理由? [英] Any good reason for passing ServletResponse as parameter?

查看:425
本文介绍了将ServletResponse作为参数传递的任何好理由?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有什么好理由 javax.servlet.Servlet 's
void service(ServletRequest req,ServletResponse res) )方法将 ServletResponse 作为参数给出,而不仅仅是返回它?

Is there any good reason why javax.servlet.Servlet's
void service(ServletRequest req, ServletResponse res) method has the ServletResponse given as parameter, instead of just returning it?

推荐答案

Java Servlet API是一个抽象,它定义了任何Java Web应用程序处理任何类型请求所需的最低要求(如果你看一下,你会注意到几乎所有的类都定义了作为接口或抽象类)。

The Java Servlet API is an abstraction and defines the minimum requirements needed by any Java Web Application to handle any kind of request (if you look at it you will notice that almost all classes there are defined as interfaces or abstract classes).

此API已由 JCP 经过不同Java Server供应商(IBM,Sun,Apache,Oracle等)就最低要求达成一致的流程,从而定义了现在被视为官方标准的内容。但是,不同的供应商有不同的方法来实现他们的servlet容器,导致现在它们各不相同(每个都有不同的功能)。

This API has been defined by the JCP after a process in which different Java Server vendors (IBM, Sun, Apache, Oracle, etc.) agreed on the minimum requirements thus defining what is considered now as the official standard. However, the different vendors have different ways of implementing their servlet containers resulting in the diverse amount of them nowadays (each of them with different features).

由于servlet容器需要跟踪两个对象(请求和响应)以正确处理两者,他们无法利用创建 ServletResponse 的责任(或HTTP变体 HttpServletResponse )给用户 - 请记住Servlet的服务方法中的内容是用户代码。因此,servlet容器在调用 service 方法之前创建并预填充请求和响应对象(使用它们自己的实现)。从用户的角度来看,只需通过接口处理它们就足够了,这也可以保护特定于供应商的代码,因为我们无法访问这两个对象的实际实现。

Since servlet containers need to keep track of both objects (the request and the response) to do a proper handling of both, they can't leverage the responsibility of creating a ServletResponse (or the HTTP variant HttpServletResponse) to the user - remember that what goes inside the Servlet's service method is user code. So, servlet containers create and prepopulate a request and response objects (using their own implementations) prior to invoke the service method. From the user point of view, just handling them through the interfaces is enough and this also protects vendor-specific code since we don't have access to the actual implementation of both objects.

然而,当定义API时,这些供应商意识到,在某些情况下,用户希望覆盖任何这些对象的默认行为,因此它们包含一组包装器( HttpServletRequestWrapper HttpServletResponseWrapper 等),可以通过用户代码进行扩展,并在servlet或过滤器中使用,以替换容器提供的默认实现。

However, when the API was defined these vendors realised that, in some cases, the user would like to override the default behaviour of any of those objects so they included a set of wrappers (HttpServletRequestWrapper, HttpServletResponseWrapper, etc.) that can be extended by user code and used in either servlets or filters to replace the default implementations provided by the container.

这篇关于将ServletResponse作为参数传递的任何好理由?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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