In the second example, you are creating a new client-side cookie (i.e. you are impersonating a browser and are sending the cookie to the server).
This means that you need to provide all the relevant information, so that the client can decide whether to send the cookie to the server or not.
In your code you correctly set the path,name and value, but the domain information is missing.
org.apache.commons.httpclient.Cookie cookie
= new org.apache.commons.httpclient.Cookie();
cookie.setDomain("localhost");
cookie.setPath("/");
cookie.setName("Tim");
cookie.setValue("Tim");
This works if what you are trying to achieve is to send a cookie to an http server.
Your second example, though, spans from an execute
method, an since you are hinting at struts2 in your tag, maybe the class containing it is meant to be a struts2 Action
.
If this is the case, what you are trying to achieve is to send a new cookie to a browser.
The first approach is to get hold of a HttpServletResponse
as in:
So your Action
must look like:
public class SetCookieAction
implements ServletResponseAware // needed to access the
// HttpServletResponse
{
HttpServletResponse servletResponse;
public String execute() {
// Create the cookie
Cookie div = new Cookie("Tim", "Tim");
div.setMaxAge(3600); // lasts one hour
servletResponse.addCookie(div);
return "success";
}
public void setServletResponse(HttpServletResponse servletResponse) {
this.servletResponse = servletResponse;
}
}
Another approach (without HttpServletResponse
) could be obtained using the CookieProviderInterceptor.
Enable it in struts.xml
<action ... >
<interceptor-ref name="defaultStack"/>
<interceptor-ref name="cookieProvider"/>
...
</action>
then implement CookieProvider
as:
public class SetCookieAction
implements CookieProvider // needed to provide the coookies
{
Set<javax.servlet.http.Cookie> cookies=
new HashSet<javax.servlet.http.Cookie>();
public Set<javax.servlet.http.Cookie> getCookies()
{
return cookies;
}
public String execute() {
// Create the cookie
javax.servlet.http.Cookie div =
new javax.servlet.http.Cookie("Tim", "Tim");
div.setMaxAge(3600); // lasts one hour
cookies.put(cookie)
return "success";
}
}
(credits to @RomanC for pointing out this solution)
If you subsequently need to read it you have two options:
- implement
ServletRequestAware
in yourAction
and read the cookies from theHttpServletRequest
- introduce a
CookieInterceptor
and implementCookiesAware
in yourAction
, the methodsetCookieMap
allows to read the cookies.
Here you can find some relevant info: