Request Wrappers and Response Wrappers

If you need to extend the functionality of request or response objects, there are wrapper classes that can wrap around current request or response. The wrapper classes implements the required interfaces so that we can pass it to any place that expects those interface implementations. These wrappers will simply delegate the calls to the default container implementation of the request and response interfaces.

Wrappers are required because the current implementation of the interface is container specific and hence you cannot extend them. However you can extend the wrappers and override only those methods that are required to be changed. The remaining method calls will be delegated to the container implementation. You may also implement the interfaces from scratch on your own, but that would be a very difficult and time consuming task.

 

API Summary for request and response wrappers

ServletRequestWrapper

  • ServletRequestWrapper class implements ServletRequest.

  • The constructor of ServletRequestWrapper sets the encapsulation:

    • public ServletRequestWrapper(ServletRequest encapsulatedReq)

    • An IllegalArgumentException if the argument passed is null

  • Two extra methods used to modify encapsulated request

    • ServletRequest getRequest()

    • void setRequest (ServletRequest encapsulatedReq)

 

HttpServletRequestWrapper

  • The HttpServletRequestWrapper class extends ServletRequestWrapper and implements HttpServletRequest

  • All methods newly implemented in this class are from HttpServletRequest

  • The constructor of HttpServletRequestWrapper sets the encapsulation:

    • public HttpServletRequestWrapper(HttpServletRequest wrappedReq)

    • An IllegalArgumentEceception is thrown if the argument passed is null

    • Despite taking HttpServletRequest as its parameter, the object is actually stored internally in the ServletRequestWrapper class as a ServleRequest. Therefore returned object by getRequest() must be casted to HttpServletRequest if it is to be used as such:

      • HttpServletRequest orig = (HttpServletRequest) wrapper.getRequest();

 

ServletResponseWrapper

  • The ServletResponseWrapper class implements ServletResponse

  • The constructor of ServletResponseWrapper sets the encapsulation:

    • public ServletResponseWrapper (ServletResponse encapsulatedResp)

    • An IllegalArgumentEceception is thrown if the argument passed is null

  • Two extra methods used to modify encapsulated response

    • ServletResponse getResponse()

    • void setResponse(ServletResponse encapsulatedResp )

 

HttpServletResponseWrapper

  • The HttpServletResponseWrapper class extends ServletResponseWrapper and implements HttpServletResponse.

  • The constructor of HttpServletResponseWrapper sets the encapsulation:

    • public HttpServletResponseWrapper (HttpServletResponse wrapped)

    • An IllegalArgumentEceception is thrown if the argument passed is null

    • This class uses its parent’s storage mechanism which is of type ServletResponse. It is therefore necessary to explicitly cast the object retrieved from the getResponse method:

      • HttpServletResponse r = (HttpServletResponse) wrapper.getResponse();

 

Steps to use wrappers

  1. Extend HttpServletRequestWrapper and HttpServletResponseWrapper to create custom wrappers.

    • E.g. MyHttpServletRequestWrapper extends HttpServletRequestWrapper {}

  2. Creater a wrapper instance over the request object:

    • E.g. HttpServletRequestWrapper myReqWrapper = new MyHttpServletRequestWrapper (request);

  3. Include or forward using this myReqWrapper passing it instead of request. It should behave exactly as before (without wrappers) now.

  4. Do similar (1-3) for HttpServletResponseWrapper with response object and include or forward using this wrapper passing it instead of response. 

  5. Now you can start making any modifications to your custom wrappers to extend or modify the functionality of request or response objects.

 

Major applications of request and response wrappers

We can override the stream behavior of request/response object. For instance, we can provide an extra layer of buffer using a wrapper with its own internal buffer independent of the output stream supplied by the container. We can pass this to other components and once we finally verify the content, then we can write it into containers output stream and thus actually committing the response. 

Wrappers are more commonly used with filters than directly with servlets using RequestDispatcher mechanism. Filters give more flexibility and can be easily added/removed just by changing the deployment descriptor configuration.

We can override the value of a header on the way from client or on the way back to client. 

public String getHeader(String header)

{

  if(header.equals("something") {

    return "somethingelse";

  }

  return ((HttpServletRequest) getRequest()).getHeader(header);

}

Note that we have to do an extra cast as the object is actually stored internally in the ServletRequestWrapper class as a ServleRequest. Therefore returned object by getRequest() must be casted to HttpServletRequest.

We may also provide default value for any header.

We may also provide new APIs and then do an explicit cast to our wrapper class from another servlet to get access to these extra APIs.

MyCustomWrapper mcw = (MyCustomWrapper)request;

mcw.myNewMethod();

However this is not a preferred thing to do as it violates many design principles. You will also have to check if the request actually contain the correct instance using an instanceof operator, which will again increase the code that needs to be written.

Tags: 

Quick Notes Finder Tags

Activities (1) advanced java (1) agile (3) App Servers (6) archived notes (2) Arrays (1) Best Practices (12) Best Practices (Design) (3) Best Practices (Java) (7) Best Practices (Java EE) (1) BigData (3) Chars & Encodings (6) coding problems (2) Collections (15) contests (3) Core Java (All) (55) course plan (2) Database (12) Design patterns (8) dev tools (3) downloads (2) eclipse (9) Essentials (1) examples (14) Exception (1) Exceptions (4) Exercise (1) exercises (6) Getting Started (18) Groovy (2) hadoop (4) hibernate (77) hibernate interview questions (6) History (1) Hot book (5) http monitoring (2) Inheritance (4) intellij (1) java 8 notes (4) Java 9 (1) Java Concepts (7) Java Core (9) java ee exercises (1) java ee interview questions (2) Java Elements (16) Java Environment (1) Java Features (4) java interview points (4) java interview questions (4) javajee initiatives (1) javajee thoughts (3) Java Performance (6) Java Programmer 1 (11) Java Programmer 2 (7) Javascript Frameworks (1) Java SE Professional (1) JPA 1 - Module (6) JPA 1 - Modules (1) JSP (1) Legacy Java (1) linked list (3) maven (1) Multithreading (16) NFR (1) No SQL (1) Object Oriented (9) OCPJP (4) OCPWCD (1) OOAD (3) Operators (4) Overloading (2) Overriding (2) Overviews (1) policies (1) programming (1) Quartz Scheduler (1) Quizzes (17) RabbitMQ (1) references (2) restful web service (3) Searching (1) security (10) Servlets (8) Servlets and JSP (31) Site Usage Guidelines (1) Sorting (1) source code management (1) spring (4) spring boot (3) Spring Examples (1) Spring Features (1) spring jpa (1) Stack (1) Streams & IO (3) Strings (11) SW Developer Tools (2) testing (1) troubleshooting (1) user interface (1) vxml (8) web services (1) Web Technologies (1) Web Technology Books (1) youtube (1)