Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The <a href="http://docs.oracle.com/javaee/5/api/javax/servlet/http/HttpServletRequest.html#getUserPrincipal%28%29" rel="nofollow noreferrer"><code>HttpServletRequest#getUserPrincipal()</code></a> as pointed out in the other answer only applies when you make use of Java EE provided container managed security as outlined <a href="http://docs.oracle.com/javaee/5/tutorial/doc/bncbe.html" rel="nofollow noreferrer">here</a>.</p> <p>If you're however homegrowing your own security, then you need to rely on the <a href="http://docs.oracle.com/javaee/5/docs/api/javax/servlet/http/HttpSession.html" rel="nofollow noreferrer"><code>HttpSession</code></a>. It's not that hard, here is an overview what you need to implement on each step:</p> <p>On login, get the <code>User</code> from the DB and store it in session in <a href="https://stackoverflow.com/tags/servlets/info">servlet's</a> <code>doPost()</code>:</p> <pre><code>User user = userDAO.find(username, password); if (user != null) { session.setAttribute("user", user); } else { // Show error like "Login failed, unknown user, try again.". } </code></pre> <p>On logout, just invalidate the session in servlet's <code>doPost()</code>. It will destroy the session and clear out all attributes.</p> <pre><code>session.invalidate(); </code></pre> <p>To check if an <code>User</code> is logged in or not, create a <a href="https://stackoverflow.com/tags/servlet-filters/info">filter</a> which is mapped with an <code>url-pattern</code> which covers the restricted pages, e.g. <code>/secured/*</code>, <code>/protected/*</code>, etcetera and implement <code>doFilter()</code> like below:</p> <pre><code>if (session.getAttribute("user") == null) { response.sendRedirect(request.getContectPath() + "/login"); // Not logged in, redirect to login page. } else { chain.doFilter(request, response); // Logged in, just continue chain. } </code></pre> <p>That's basically all.</p> <h3>See also:</h3> <ul> <li><a href="https://stackoverflow.com/questions/1026846/how-to-redirect-to-login-page-when-session-is-expired-in-java-web-application/32627461#32627461">How to redirect to Login page when Session is expired in Java web application?</a></li> <li><a href="https://stackoverflow.com/questions/9965708/how-to-handle-authentication-authorization-with-users-in-a-database">How to handle authentication/authorization with users in a database?</a></li> </ul>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload