Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a session cookie inside a controller

I'm new to Tomcat, servlets and Spring Web. I'm coming from a PHP background so I'm a little disoriented to say the least. I want a controller to create a session cookie for me.

I've been told that I can get the session like this in a standard servlet:

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
  // Somewhere inside the method...
  HttpSession session = request.getSession(true);

  // Set a cookie
      session.setAttribute("hello", "world");

  // More stuff...
}

How does this translate into the Spring Web MVC way of doing things? Can I create session cookies inside a controller?

like image 688
Pieter Avatar asked Dec 17 '22 14:12

Pieter


1 Answers

What you are doing in your example have nothing to do with cookies. session.setAttribute("key", valueObject); Sets a java-object in the session. The session is kept at the server. The sessionid is the only thing communicated back to the client. It can be a cookie or it can be in the URL. The attributes in the session is not serialized to strings.

Cookies on the other hand are strings that are sent back to the client. It is the clients responsibility to store their cookies (and some people turn them off) and return them to the server.

Setting a cookie value from a complex object-graph will require serialization and deserialization. A session attribute will not.

If you want to read a cookie, use this:

@CookieValue("key") String cookie

In the controller parameter list. The cookie variable will be populated with the value from the cookie named "key".

To set a cookie, call:

response.addCookie(cookie);
like image 106
Gunslinger Avatar answered Dec 19 '22 03:12

Gunslinger