DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Cookies Revisited: A Networking Solution for Third-Party Cookies
  • A Beginner's Guide to Spark UI: Concepts and How to Use It
  • Multi-Tenant .NET Applications With Keycloak Realms
  • Observability and DevTool Platforms for AI Agents

Trending

  • How To Build Resilient Microservices Using Circuit Breakers and Retries: A Developer’s Guide To Surviving
  • Monolith: The Good, The Bad and The Ugly
  • How To Introduce a New API Quickly Using Quarkus and ChatGPT
  • How to Create a Successful API Ecosystem

Disable multiple logins for same user - Servlets and Sessions

By 
Waqas Memon user avatar
Waqas Memon
·
Sep. 09, 13 · News
Likes (4)
Comment
Save
Tweet
Share
51.5K Views

Join the DZone community and get the full member experience.

Join For Free

There are many approaches including the database flag for a user to know whether a user is logged in currently or not. Database solution takes lot of work and amount of time to implement and has many problems including browser close should also log-out for the user does not wait so many minutes before sessions get invalidated automatically. HttpSessionListener must also be implemented in the database solution, hence I will strongly discourage the use of this approach, which involves re-inventing the wheel again and again because every developer has to do it on his own for his application. 

HttpSessionBindingListener

There are two ways users can be restricted to login from multiple sessions, either previous session of user be removed, or new session of user be disallowed. In both approaches I would recommend using HttpSessionBindingListener. Implementing this interface requires providing implementation for boolean equals(Object other),int hashCode(), voidvalueBound(HttpSessionBindingEvent event) and voidvalueUnbound(HttpSessionBindingEvent event).

public class LoginDto implements HttpSessionBindingListener {
  
  private String accountId
  private boolean alreadyLoggedIn;
  
  //setters and getters of all your User dto including accountId...

  private static Map<User, HttpSession> logins = new HashMap<User, HttpSession>();

  @Override
  public boolean equals(Object other) {
    return (other instanceof LoginDto) && (getAccountId() != null) ? 
     getAccountId().equals(((LoginDto) other).getAccountId()) : (other == this);
  }

  @Override
  public int hashCode() {
    return (getAccountId() != null) ? 
     (this.getClass().hashCode() + getAccountId().hashCode()) : super.hashCode();
  }

  @Override
  public void valueBound(HttpSessionBindingEvent event){
    HttpSession oldSession = logins.get(this);
    if (oldSession != null) {
      alreadyLoggedIn = true;
    } else {
      logins.put(this, event.getSession());
    }

    //Note: you can comment above code and remove comments from below code. removing comments from 
 //below code will remove old session of user and let the user log-in from new session.

    //HttpSession session = logins.remove(this);
    //if (session != null) {
    //  session.invalidate();
   //}
   //logins.put(this, event.getSession());  
  }

  @Override
  public void valueUnbound(HttpSessionBindingEvent event) {
    logins.remove(this);
  }

}//end of class LoginDto

 You do not need to do anything else except storing a LoginDto in session when a user logs in, or removing it on session timeout. Http Session Binding Listener should automatically invoke valueBound and valueUnbound methods whenever LoginDto is bound to session, not to mention, browser's close or in cases when users leave unexpectedly.

Example servlet code

if(//user is valid and validated from database etc...) {
    session.setAttribute("UserContext", dto); //this will invoke valueBound method of LoginDto.
    if(dto.isAlreadyLoggedIn()){
      session.removeAttribute("UserContext"); //this will invoke valueUnbound method of LoginDto
      throw new MyCustomException("You are already logged in from a different session. Please logout first.");
    }
}else {
    session.setAttribute("UserContext", null);
}
Session (web analytics)

Opinions expressed by DZone contributors are their own.

Related

  • Cookies Revisited: A Networking Solution for Third-Party Cookies
  • A Beginner's Guide to Spark UI: Concepts and How to Use It
  • Multi-Tenant .NET Applications With Keycloak Realms
  • Observability and DevTool Platforms for AI Agents

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!