java - Spark micro framework - save sessions in database? -
how configure rdbms (mysql) session store spark framework (the java micro web framework available @ http://sparkjava.com/)?
the reason ask want user sessions remain valid if jetty, spark runs on, has restarted.
actually there option store sessions in database. use ebean orm, can other orm pure sql.
assume have user class , usersession class.
what should check whether there active session. if exists , has no user bound — pass authentication. if not exist — check if jsessionid
cookie exists , has record in usersession table. if there such session retrieve user, create new session , bind user it.
two class listings below pretty self-explanatory. call user.getauthenticateduser()
every time tries access uri authenticated users. call user.addauthenticateduser(req, user)
@ successful login attempt.
user class:
@data @entity @table(name = "users") public class user { private static final string user_session_id = "sessionid"; @id long id; string login; string password; string email; integer role; public static user authuser(user user) { return ebean.find(user.class).where() .eq("login", user.login) .eq("password", user.password) .findunique(); } public static void addauthenticateduser(request req, user u) { session session = req.session(); ebean.save(new usersession(u, session.id())); req.session().attribute(user_session_id, u); } public static user getauthenticateduser(request req, response res) { user user = null; session session = req.session(false); if (session == null) { usersession usersession = usersession.getsession(req.cookies().get("jsessionid")); if (usersession != null) { user = usersession.getuser(); usersession.delete(); addauthenticateduser(req, user); } } else { user = session.attribute(user_session_id); } // redirect login form if (user == null) { res.redirect("/login"); halt(); } return user; } }
usersession class:
@data @entity @table(name = "sessions") public class usersession { @manytoone(fetch = eager) @joincolumn(name = "uid") private user user; private string session; private timestamp taken; public usersession(user u, string sessionid) { user = u; session = sessionid; taken = new timestamp(system.currenttimemillis()); } public static usersession getsession(string session) { return ebean.find(usersession.class).where().eq("session", session).findunique(); } public void delete() { sqlupdate deletequery = ebean.createsqlupdate("delete sessions uid = :uid , session = :session"); deletequery.setparameter("uid", user.id); deletequery.setparameter("session", session); deletequery.execute(); } }
Comments
Post a Comment