Working with cookies in Struts 2
It appears that struts only supports reading cookies, you have to go to the servlet response to actually set a cookie.
So it is better to go directly to the servlet request/response objects for both reading and writing:
For this your action class should implement
Now you can set cookie something like this:
And get the cookie value something like this:
So it is better to go directly to the servlet request/response objects for both reading and writing:
For this your action class should implement
two interfaces namely:
ServletResponseAware and ServletRequestAware like this:
public class MyActionClass extends ActionSupport implements ServletResponseAware, ServletRequestAware {
}
And following line of code should be included in action class.
protected HttpServletResponse servletResponse;
@Override
public void setServletResponse(HttpServletResponse servletResponse) {
this.servletResponse = servletResponse;
}
protected HttpServletRequest servletRequest;
@Override
public void setServletRequest(HttpServletRequest servletRequest) {
this.servletRequest = servletRequest;
}
Now you can set cookie something like this:
public String execute(){
// Save to cookie
Cookie cookie = new Cookie("cookieUser", userId);
cookie.setMaxAge(60*60*24*365); // Make the cookie last a year
servletResponse.addCookie(cookie);
return "success";
}
And get the cookie value something like this:
public Cookie getCookieValue(String cookieName){
Cookie cookies [] = servletRequest.getCookies ();
Cookie myCookie = null;
if (cookies != null)
{
for (int i = 0; i < cookies.length; i++)
{
if (cookies [i].getName().equals (cookieName))
{
myCookie = cookies[i];
break;
}
}
}
return myCookie;
}
Comments