MayoMan
MayoMan

Reputation: 4917

Using Tomcat to prevent concurrent User session from same PC

I have looked at a few good examples on SO here such as How to Prevent Concurrent User Logins in PHP/MySQL Site? and they describe the problem I'm trying solve. Basically only allow a given user to open One and Only one session at a time, be it from the same PC or 2 different PCs. So querying a DB for a LoggedIN/Not LoggedIN flag is the simplest workable solution. How to implement this is my problem.
Having session validation added to each page which gets run each time the page is requested is not workable as it would require modifying all our JSPs ( Long story but we don't have a common Header file ) Is there any way I can reconfigure Tomcat to run some validation checks on each request to query the DB ? Maybe using valves or some other means? I don't have a lot of Tomcat experience so this is why I ask. Thnx

Upvotes: 2

Views: 2287

Answers (1)

Sean
Sean

Reputation: 7737

Instead of changing all your JSP files, you can look at using a Filter. The filter will allow you to intercept the requests and perform some level of validation on the request.

Then however you decide to check for active sessions is up to you.

public class SessionCheckFilter implements Filter {
   public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) 
     throws IOException, ServletException {

   //Your validation code here.
   boolean returnValue = YourClass.performSessionValidation();
   if(returnValue){
      //Do Something
   }else{
     //Do Something else
   }

   //standard filter call
   chain.doFilter(req, res);
}

And then in the web.xml map the servlet to your code. (change according to your needs)

<filter>
    <filter-name>SessionCheckFilter</filter-name>
    <filter-class>com.stackoverflow.SessionCheckFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>SessionCheckFilter</filter-name>
    <url-pattern>*.jsp</url-pattern>
</filter-mapping>

For more information see the servlet-filter info page here on SO

Upvotes: 2

Related Questions