Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
I have two controllers. I'm trying to put the logged user into the session in one method, and then get it in a other method. But the sessions are different, how to fix it?
@RestController
public class UserController {
@Autowired
private UserService userService;
@RequestMapping(value = "/user/signIn", method = RequestMethod.POST)
public ResponseEntity<DataUser> signIn(@RequestBody @Valid SignInUser signInUser,
HttpSession session) {
User user = userService.getUser(signInUser.getEmail(), signInUser.getPassword());
session.setAttribute("user", user);
DataUser dataUser = new DataUser((User) session.getAttribute("user"));
return ResponseEntity.ok(dataUser);
@RestController
public class MessageController {
@Autowired
private MessageService messageService;
@RequestMapping(value = "/data/message", method = RequestMethod.POST)
public Message save(@RequestBody NewMessage newMessage,
HttpSession session) {
System.out.println(session.getAttribute("user"));
Message message = new Message(newMessage);
LocalDateTime dateTime = LocalDateTime.now();
message.setDateTime(dateTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli());
message.setNumberRating(0);
return messageService.save(message);
session.getAttribute("user") is null
–
–
The common behavior of sessions for WebApps is that your client is identified, commonly through a cookie called JSESSIONID
, but for REST
calls you do not have such possibility you probably don't even call from a browser, so you can not say that one request is coming from the same "machine/user" as this other request.
In order to do that you'll need to:
Properly configure and enable spring session
Have a way identify your requests, unique IDs of some sort.
And every new request have to inform you the same identificator, so you can ask for spring something like "give me the session for this user".
Here is a more detailed tutorial for Spring Session.
–
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.