• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

double about change request header in HttpServletRequestWrapper

 
Pham Hoai Van
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I got this question:
which three are true about the HttpServletRequestWrapper class:
A. The HttpServletRequestWrapper is an example of Decorator pattern
B. The HttpServletRequestWrapper can be used to extend the functionality of a servlet request
C. A subclass of HttpServletRequestWrapper can not modify the default behaviour of getReader method
D. An HttpServletRequestWrapper may be used only by a class implementing the javax.servlet.Filter interface
E. An HttpServletRequestWrapper can not be used on the request passed to the method RequestDispatcher.include method
F. An HttpServletRequestWrapper may modify header of a request within an object implementing the javax.servlet.Filter interface

The given correct answer is A B & F. But i think it should be A B & D. I digged into the API and source code of HttpServletRequestWrapper but found noway to modify header of a request. Any comment or guide, pls.
 
Dee Brown
Ranch Hand
Posts: 94
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Brief examination suggests it is just A,B. Unsure why you would want to modify request headers in the first place. Header manipulation occurs on the response side of the loop.

Regarding restricting HttpServletRequestWrapper usage to the Filter interface, another potential usage would be in doGet/doPost before performing an include/forward, so D is not correct. The only restriction is having access to the object being wrapped.
 
Ankur Gargg
Ranch Hand
Posts: 55
Java jQuery Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi

F is correct.
As you can override the getHeader() method in your class to return a modified value of header.


public String getHeader(String name) {
//get the request object and cast it
HttpServletRequest request = (HttpServletRequest)getRequest();

//if we are looking for the "username" request header
if("username".equals(name)) {
//loop through the cookies
Cookie[] cookies = request.getCookies();


//if cookies are null, then return null

if(null == cookies) {
return null;

}



for(int i=0; i < cookies.length; i++) {

//if the cookie's name is "username"

if("username".equals(cookies[i].getName())) {

//get its value and return it

String val = cookies[i].getValue();

return val;

}

}

}



//otherwise fall through to wrapped request object

return request.getHeader(name);
}

Using this you can return a new header altogether.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic