FGHJ FGHJ - 5 months ago 30
Java Question

Spring @ResponseBody can not use session

I have angular2 app and use Tomcat with spring for getting data. I don't want any page reloads or redirects, all I need is data, so all responses from server have @ResponseBody annotations.

My problem is, that because of this annotation I can not get users session variable. When I log in I create session, store user data in it but can not get it with next call.

@JsonIgnoreProperties(ignoreUnknown = true)
@RequestMapping(method = RequestMethod.POST)
public String login(HttpServletRequest REQ, @RequestBody String BODY) throws Exception
...check if all ok...
REQ.getSession().setAttribute("user", user);
... return user data...

Is there any other way I can send my data back to client, together with the data needed, to be able to use session.

Problem is not on server side but client. Angular is not sending cookie JSESSIONID at cross domain requests by default.


First check your request/response (for example in Chrome dev tools). Tomcat creates new cookie named JSESSIONID to bind client with server session object, so look for this one in your login method response header. Then make sure you are sending this cookie back to your server in next request. Session creation has nothing to do with Spring or @ResponseBody, its lifetime is managed by container (Tomcat).

Also, if you are making cross domain requests, check this answer.