So, I am working on creating a simple chat app. I'm not using spring security.
So, in front end, the user enters their name which is handled by this controller.
@PostMapping("/addUser")
public User addUser(@RequestBody String name, HttpServletRequest request) {
String session = (String) request.getSession().getAttribute("sessionId");
System.out.println("Session id is " session);
User newUser = new User(name, session);
userService.addUser(newUser);
System.out.println(newUser);
return newUser;
}
I'm using pre handler method handler interceptor to generate session id for the user. Below is the code:
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("Its working");
// TODO Auto-generated method stub
if(request instanceof HttpServletRequest) {
HttpServletRequest servletRequest = (HttpServletRequest) request;
HttpSession session = servletRequest.getSession();
session.setAttribute("sessionId", session.getId());
System.out.println("Connected with session id : " session.getAttribute("sessionId"));
}
return true;
}
So, I want to make sure that whenever users are inactive for cetain time, I want to end the session for that user and also remove that user from the arraylist of user where I have kept all the users who register by entering their name (in the front end).
Is it possible to achieve without sprin security or do I have to learn spring security to implement it.
I did try using task scheduler but then I found out in some article that its impossible to call HttpSession there.
CodePudding user response:
You can set the session life (time it can be inactive before being killed) with server.servlet.session.timeout=30m
You can take the user out of your list by implementing a HttpSessionListener.sessionDestroyed
- spring-boot-session-listener
CodePudding user response:
if you use WebSocket, You can use heartbeat for your session, on the other hand, if you use rest then you should keep the session in memory(redis, hazelcast, or in-memory (singleton object) like map<key, session>, (keep in mind, the client should send a disconnect request or you should control it in the backend)