Link to home
Start Free TrialLog in
Avatar of deltanins
deltanins

asked on

Adding a cookie to a request

Is there any way to add a cookie to a request? I have an intermediate stage (server) in between the users request and the server that processes the request and forms a response. At this intermediate stage I want to add more cookies onto the request before forwarding the request to its final destination, but as far as I've seen HttpServletRequest doesn't have an addCookie() method. Has anyone found a way to get around this?
Avatar of bloodredsun
bloodredsun
Flag of Australia image

You could use setAttribute() but this has warnings.
Just create the cookie and add it to the HttpServletResponse :

      Cookie cookie = new Cookie("MyCookieName", "somevalue");

      //--- default expiration to 1 day...
      cookie.setMaxAge(60*60*24);
      cookie.setPath("");

     //--- you could also set the cookie domain if you want...
     // cookie.setDomain("yahoo.com");

     httpResponse.addCookie(cookie);
BTW, just for clarification wrt above snippet :

   cookie is a javax.servlet.http.Cookie
   httpResponse is a javax.servlet.http.HttpServletResponse


Avatar of deltanins
deltanins

ASKER

I don't want to set the cookie to the response, because I want it added to the request that goes to the internal server, not the response that goes back to the user.

Investigating setAttribute().....
ASKER CERTIFIED SOLUTION
Avatar of lhankins
lhankins
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Yes, I've code downstream that needs the cookie to be in the request, and it's all Java code.
How would I write my own code to add the cookie to the request? I've tried to find the method details for addCookie when it's added to a response, but can't find the source code anywhere. Is it a case of adding/amending the header on the request?
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
thanks everyone.