|
Java™ by example!
|
|
|
How do I create a session-enabled Servlet?
The key object for it is javax.servlet.http.HttpSession. Servlet engine is able to track users by use of cookies or additional URL parameters, at your choice. This goes completely behind the scenes. For every session, a HttpSession object is created and kept. It has mechanisms to store values (very much like a hashtable) so that you can set necessary number of name/value pairs in one servlet and then use them in another. These values are all stored on server side, client only keeps otherwise-meaningless numeric session handle. HttpSession objects do not always exist, but a HttpSession object can be easily created during every request. So, let's store user login name and password in a session object on a login page and check them on every other page we want to protect by password. Here's an example. We'll need a simple utility class.
 public class Utils { /// inner class for login info storage public static class loginInfo { public String login; public boolean active; // any other fields you'd need } // Handy convenience methods public static String nvl(String x, String def) { return (x == null? def : x); } public static String nvl(String x) { return (x == null? "" : x); }
// gets user loginInfo for login if password matches, else null. loginInfo getLoginInfo(String login, String pwd) { loginInfo ret = null; if (login == null) login = ""; if (pwd == null) pwd = ""; // replace the 'if' with your database access code or such... if (pwd.equals.("snoopy")) { ret = new loginInfo(); ret.login = login; ret.active = true; } return ret; } /** Checks auth info associated with session. If auth info is wrong, null is returned. If session is new, null is returned. Else value of getLoginInfo(...) is returned. Generally, if a non-null is returned, proceed, else redirect to login page. */ public loginInfo checkAuth(HttpSession ses) { if (ses == null) return null; if (ses.isNew()) { return null; } else { String p_login = nvl((String)ses.getValue("login")); String p_pwd = nvl((String)ses.getValue("password")); loginInfo li = getLoginInfo(p_login, p_pwd); if (!li.active) li = null; return li; } } }
|
Our 'login page'. Real page would produce a HTML form.
 public class login_page extends HttpServlet { ... public void doGet(HttpServletRequest req, HttpServletResponse resp) { try { resp.setContentType("text/plain"); PrintWriter w = resp.getWriter(); // params String p_login = req.getParameter("login"); String p_pwd = req.getParameter("pwd"); boolean must_redirect = (p_login != null) && (p_pwd != null); // check if we have a session HttpSession ses = req.getSession(true); if (req.getParameter("logout") != null) { ses.invalidate(); // make servlet engine forget the session w.println("You have been logged out!"); resp.sendRedirect("logged-out.html"); return; } if (ses.isNew()) { // new session has nothing, set it up ses.putValue("login", Utils.nvl(p_login)); ses.putValue("password", Utils.nvl(p_pwd)); } else { // session is not new, try to set credentials p_login = nvl(p_login, (String)ses.getValue("login")); p_pwd = nvl(p_pwd, (String)ses.getValue("password")); // get credentials Utils.loginInfo li = Utils.getLoginInfo(p_login, p_pwd); if (li != null) { ses.putValue("login", p_login); ses.putValue("password", p_pwd); w.println("You are logged on as "+p_login); w.println("Is your account active? "+li.active); if (must_redirect && li.active) { resp.sendRedirect("protected-page"); return; } } else { w.println("You are not logged in."); } } } catch (IOException e) {} } ... }
|
And our sample 'protected' page; all other protected pages will follow this design.
 public class protected_page extends HttpServlet { ... // do the show public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException { HttpSession ses = req.getSession(true); // authorize Utils.loginInfo li = Utils.checkAuth(ses); if (li == null) { resp.sendRedirect("login_page?redirect="+HttpUtils.getRequestURL(req)); return; } try { PrintWriter w = resp.getWriter(); w.println("Here we are, logged in as "+li.login); } catch (IOException e) { // moan here if things go wrong } } }
|
Of course, things should be combed up, real HTML output to be made, string constants used instead of "login" strings spilled over the place, etc. Sssion timeout is not handled here; see HttpSession object documents on how to set it per session and servlet engine docs on how to set the default value.
Further Information
Author of answer: hal9000
Comments to this answer are only viewable by members. Login or become a member!
|
|
|
|
|