Billworth Vandory
Billworth Vandory

Reputation: 5053

Why use the HttpServletResponseWrapper vs extending HttpServletResponse directly

I'm looking at the decorator HttpServletResponseWrapper and I'm wondering 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

Upvotes: 2

Views: 3337

Answers (3)

skaffman
skaffman

Reputation: 403551

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.

Upvotes: 2

Carey
Carey

Reputation: 1178

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.

Upvotes: 4

Will Hartung
Will Hartung

Reputation: 118734

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.

Upvotes: 2

Related Questions