开发者

Why use the HttpServletResponseWrapper vs extending HttpServletResponse directly

I'm looking at the decorator HttpServletResponseWrapper and I'm 开发者_如何学Gowondering what is the benefit in using this wrapper vs simply extending HttpServletResponse and overriding what you need? What is the benefit in having this intermediary wrapper which just delegates all its methods?

thx


It saves you from implementing a lot of boilerplate if you’re mostly wrapping another HttpServletResponse. But more importantly, it means your filter will still work when a new version of the JavaEE specification is released with new methods on the httpServletResponse interface, instead of failing at runtime (and compile time) because you don’t implement the new interface.


HttpServletResponse is an Interface, *Wrapper is a class implementing that interface.

By extending *Wrapper, you don't have to implement all of the boiler plate, just the few bits you want.


While @Carey's response is correct, it's not the most important reason for the wrapper class.

The Servlet spec says that if you forward a request or response inside a servlet/filter/JSP, then the request and response objects must be the same request/response objects that the container originally passed in, or must be wrappers around them, using the supplied wrapper classes.

So for filters that want to override the behaviour of the supplied request/response objects, they are required to extend the wrappers, rather than just create a new request/response class from the interfaces.

Note that some servlet containers (such as older versions of Tomcat), ignore this part of the spec.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜