The correct way to set cookies in Struts2

I took the following code example from the Struts2 tutorial, the purpose of which is to set a cookie in the Action class, then the jsp page should extract the contents from the cookie and then display it.

LoginAction Class:

public class LoginAction implements Action,ServletResponseAware{ private HttpServletResponse response; ... public void setServletResponse(HttpServletResponse response) { this.response=response; } public String execute() throws Exception { Cookie c= new Cookie("user",getUsername()); c.setMaxAge(60*60); response.addCookie(c); return SUCCESS; } 

JSP page:

  <html> <head> <title>Cookie Success Page</title> </head> <body> <br/>Welcome ${cookie.user.value}, thanks for logging in. </body> </html> 

Now the problem is that ${cookie.user.value} will always display as empty, no matter what username I provided.

Perhaps this is not a good way to set cookie values ​​in Struts2?

+4
source share
2 answers

cookie is just a Map backstage. To access the map interface from EL, use ${cookie["user"].value}

+2
source

To create cookies, the HttpServletResponse should work. It worked for me using the servletConfig interceptor and creating setter / getter methods for HttpServletRespose .

0
source

All Articles