Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The DB-independent approach would be to let the <code>User</code> have a <code>static Map&lt;User, HttpSession&gt;</code> variable and implement <a href="https://docs.oracle.com/javaee/7/api/javax/servlet/http/HttpSessionBindingListener.html" rel="noreferrer"><code>HttpSessionBindingListener</code></a> (and <a href="http://docs.oracle.com/javase/8/docs/api/java/lang/Object.html#equals-java.lang.Object-" rel="noreferrer"><code>Object#equals()</code></a> and <a href="http://docs.oracle.com/javase/8/docs/api/java/lang/Object.html#hashCode--" rel="noreferrer"><code>Object#hashCode()</code></a>). This way your webapp will still function after an unforeseen crash which may cause that the DB values don't get updated (you can of course create a <code>ServletContextListener</code> which resets the DB on webapp startup, but that's only more and more work).</p> <p>Here's how the <code>User</code> should look like:</p> <pre><code>public class User implements HttpSessionBindingListener { // All logins. private static Map&lt;User, HttpSession&gt; logins = new ConcurrentHashMap&lt;&gt;(); // Normal properties. private Long id; private String username; // Etc.. Of course with public getters+setters. @Override public boolean equals(Object other) { return (other instanceof User) &amp;&amp; (id != null) ? id.equals(((User) other).id) : (other == this); } @Override public int hashCode() { return (id != null) ? (this.getClass().hashCode() + id.hashCode()) : super.hashCode(); } @Override public void valueBound(HttpSessionBindingEvent event) { HttpSession session = logins.remove(this); if (session != null) { session.invalidate(); } logins.put(this, event.getSession()); } @Override public void valueUnbound(HttpSessionBindingEvent event) { logins.remove(this); } } </code></pre> <p>When you login the <code>User</code> as follows:</p> <pre><code>User user = userDAO.find(username, password); if (user != null) { sessionMap.put("user", user); } else { // Show error. } </code></pre> <p>then it will invoke the <code>valueBound()</code> which will remove any previously logged in user from the <code>logins</code> map and invalidate the session.</p> <p>When you logout the <code>User</code> as follows:</p> <pre><code>sessionMap.remove("user"); </code></pre> <p>or when the session is timed out, then the <code>valueUnbound()</code> will be invoked which removes the user from the <code>logins</code> map.</p>
 

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