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 ...

Get Head First Servlets and JSP, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.