I’m working on a homework project where we implement sessions (can’t use HTTPSession) using cookies and storing session data. We’re supposed to store in memory and not an external database.
To keep things global to the instance and threadsafe, I have a singleton class SessionTable which contains a synchronized LinkedHashMap of SessionData objects.
SessionTable
public class SessionTable implements Serializable{
private static final long serialVersionUID = 3563658006793791512L;
private Map<String, SessionData> table;
private SessionTable(){
this.table = Collections.synchronizedMap(new ExpiryLinkedHashMap<String, SessionData>());
}
private static class SessionTableHolder {
public static final SessionTable instance = new SessionTable();
}
public static SessionTable getInstance() {
return SessionTableHolder.instance;
}
}
SessionSaver Servlet
public class SessionSaver extends HttpServlet {
public SessionSaver() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
SessionTable sessionTable = (SessionTable) getServletContext().getAttribute("table");
[...]
}
}
ServletListener
Based on another question here at SO I tried this method of using a listener (instead of adding the table in the constructor of the Servlet, which didn’t work). I added it in my web.xml too.
@WebListener
public class ServletListener implements ServletContextListener {
public void contextInitialized(ServletContextEvent arg0) {
arg0.getServletContext().setAttribute("table", SessionTable.getInstance());
}
}
Basically, I think I have my logic working correctly to store all the values I need in cookies, but none of this is getting persisted in the table, so when a new request comes in it thinks its a new user and always gives back a brand new cookie. What am I doing wrong? How can I get save this between requests?
I don’t see any code saving some values in your table, however the entire code looks fine (I mean that there should be one instance of table). Does your client resend previously received cookies (
Cookieheader)? Otherwise, it would be treated as a new client, sending request for the very first time.