Pieter
Pieter

Reputation: 32755

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?

Upvotes: 5

Views: 15828

Answers (3)

Gunslinger
Gunslinger

Reputation: 747

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);

Upvotes: 6

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340713

In Java Servlets (and Spring MVC in particular) you don't interact with session cookie directly, actually properly written servlet based application should work without cookies enabled, automatically falling back to URL based session id.

The way you provided is correct, although Spring is giving you much better (higher level) approaches like session-scoped beans. This way you never interact with the session itself.

Upvotes: 4

Mark Pope
Mark Pope

Reputation: 11264

You can get access to the HttpSession object by including it as a parameter in your controller's method(s):

public String get(Long id, HttpSession session) {

}

Spring will inject the current HttpSession object for you, and from there you can set attributes (like you did in your question).

Upvotes: 3

Related Questions