Wrappers rock

The wrapper classes in the servlet API are awesome—they implement all the methods needed for the thing you’re trying to wrap, delegating all calls to the underlying request or response object. All you need to do is extend one of the wrappers, and override just the methods you need to do your custom work.

You’ve seen support classes in the J2SE API, of course, with things like the Listener adapter classes for GUIs. And you’ve seen them in the JSP API with the custom tag support classes. But while those support classes and these request and response wrappers are all convenience classes, the wrappers are a little different because they, well, wrap an object of the type they implement. In other words, they don’t just provide an interface implementation, they actually hold a reference to an object of the same interface type to which they delegate method calls. (By the way, this has nothing whatsoever to do with the J2SE “primitive wrapper” classes like Integer, Boolean, Double, etc.)

image with no caption

Whenever you want to create a custom request or response object, just subclass one of the convenience request or response “wrapper” classes.

A wrapper wraps the REAL request or response object, and delegates (passes through) calls to the real thing, while still letting you do the extra things you need for your custom request or response.

Creating a specialized version of a request or response is such a common approach when creating filters, that Sun has created four “convenience” classes to make the job easier:

  • ServletRequestWrapper

  • HttpServletRequestWrapper

  • ServletResponseWrapper

  • HttpServletResponseWrapper

Note

Although not explicitly listed in the official objectives, you MIGHT see “Decorator” on the exam.

If you’re familiar with regular old (non-J2EE) design patterns, then you probably recognize this wrapper classes as an example of using a Decorator pattern (although it is also sometimes called Wrapper pattern.) The Decorator/Wrapper decorates/wraps one kind of an object with an “enhanced” implementation. And by “enhanced”, we mean “adds new capabilities” while still doing everything the original wrapped thing did.

It’s like saying, “I’m just a BETTER version of the thing I’m wrapping—I do everything it does, and more.” One characteristic of a Decorator/Wrapper is that it delegates method invocations to the thing it wraps, rather than being a complete replacement.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset