Creating a session cookie inside the controller

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

I was told that I can get a 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 to Spring Web MVC mode? Can I create session cookies inside the controller?

+4
source share
3 answers

In Java Servlets (and Spring MVC in particular) you do not interact directly with the session cookie, in fact, a correctly written servlet-based application should work without cookies enabled, automatically returning to the URL-based session identifier.

As you pointed out correctly, although Spring gives you much better (higher levels) approaches, such as beans session scope , that way, you never interact with the session itself.

+4
source

What you do in your example has nothing to do with cookies. session.setAttribute ("key", valueObject); Specifies a java object in a session. The session is stored on the server. Sessionid is the only thing passed to the client. It can be a cookie or it can be in a URL. Attributes in a session are not serialized for strings.

Cookies, on the other hand, are strings that are sent back to the client. The client is required to store their cookies (and some disable them) and return them to the server.

Setting a cookie value from a complex graphic object will require serialization and deserialization. The session attribute will not be.

If you want to read a cookie, use this:

 @CookieValue("key") String cookie 

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

To set a cookie, call:

 response.addCookie(cookie); 
+5
source

You can access the HttpSession object by including it as a parameter in your controller method:

 public String get(Long id, HttpSession session) { } 

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

+2
source

All Articles