Java EE uses listeners to implement the same user can only have one online

Source: Internet
Author: User

Here we are talking about the users who have landed or will be logged in, the visitors are not within the scope of the discussion. This should be easy for everyone to understand.

So what should we do to achieve the same user can only have one online such a small function?
One might imagine this: "Isn't that easy?" As long as in the database with a field to mark the user's state, such as if the user logged in the state set to 1, quit the user's status is set to 0,ok, done. "

But is that really the case? Actually, not all of them. Why do you say that? In fact, if your idea is the same or similar to the above, it should be said to have made a more serious mistake. Let me give you an example to illustrate it. Now the vast majority of sites have landing and exit two features it? Well, the idea above is only for these two functions to use. But have you ever thought about it? If there is a user right now, but this situation is a bit special, the user logged on but the user will not point out, and then left or left or busy other things to go, anyway, this user landed on whatever else, he hung there. This situation is allowed and is a more common situation. And if that's the case, is that the assumption you think is right? That's not true! People who know a bit about the session should know that the default destruction time in Java is greater than or equal to 30 minutes, if you do not configure the session's life cycle, according to the above assumptions, so long as the user logged on, At this point the user's status is set to 1, in a time greater than 30 minutes if the user did not make any request to the server, then the session will be destroyed, notice, then the session life cycle after the end of automatic destruction, not the user click the Exit button to destroy, Then this will not trigger the user Exit event, the user's state you can not change, that is, if you follow the above idea, you think, if you encounter such a situation, the user's status has been 1, then the user would like to log on again will not landing. Obviously, this is wrong.

What should be done to solve this problem? You should know the title of this article. You can use the Java listener to solve this problem. At the beginning of programming you should have such an understanding:

When the user accesses a website through the network, if it is the first visit, then a session will be created on the server side of the website to save some information belonging to this user. When the session is created, it actually triggers a sessioncreated event, and similarly, when the user exits normally or the user logs on without exiting and when the session ends, a sessiondestroyed event is triggered. These two events can be heard and captured by the Httpsessionlistener listener. That would solve the problem.

I have a lot of words, friends don't mind ha. Okay, here's a look at the code.

Note: In order to demonstrate the simplicity, I do not do the user encapsulation, and do not use the database, the same I do not add any SSH framework support, I know you all understand. Do not understand can give me a message. I'm going to use the servlet directly to simulate this. I directly save the user login information to a ServletContext object. By the way I also briefly say ServletContext, fear that some people do not understand ServletContext. The ServletContext object is created the first time your project starts the server, this object is created only once, is unique, you can use Servletcontextlistener this listener to listen to.

LOGIN.JSP:

<%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%>
<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >



<title> User Login </title>


<body>
<form action= "/online/servlet/loginservlet" method= "POST" >
<table>
<tr>
<td> User Nickname:</td>
<td><input type= "text" name= "username"/></td>
</tr>
<tr>
<td> User Password:</td>
<td><input type= "password" name= "pwd" size= "/></td>"
</tr>
<tr>
<td> </td>
<td><input type= "Submit" value= "Login"/></td>
</tr>
</table>
</form>
</body>

HOME.JSP:

<%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%>
<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >



<title> Users Home </title>


<body>
User ${user} landed successfully! <BR/>

</body>

ERROR.JSP:

<%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%>
<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >



<title> Friendly Tips </title>
<script type= "Text/javascript" >
function warn () {
Alert ("You are already logged in online and cannot log in repeatedly!") ");
}
</script>


<body onload= "warn (); >
You have logged in online and cannot log in again! <br>
<a href= "/online/login.jsp" > Back home </a>
</body>

Let's take a look at the landing servlet.

Loginservlet:

Package com.ljq.servlet;

Import java.io.IOException;
Import java.util.ArrayList;

Import Javax.servlet.ServletContext;
Import javax.servlet.ServletException;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;

@SuppressWarnings ("Serial")
public class Loginservlet extends HttpServlet {

public void doget (HttpServletRequest request, httpservletresponse response)
Throws Servletexception, IOException {
Created the first time the project is started, the project is created only once, only
ServletContext context = This.getservletcontext ();

String url= "/online/home.jsp";

String Username=request.getparameter ("username");
Username=new String (username.getbytes ("iso-8859-1"));

Get the list of users, the first time to get empty
Arraylist<string> users= (arraylist<string>) context.getattribute ("Users");
When the first user logs on
if (users==null) {
Users = new arraylist<string> ();
Users.add (username);
Context.setattribute ("Users", users); Saves the first user's name to a ServletContext object
Non-first User login
}else{
for (String user:users) {
If the user is already logged in, ask error.jsp not to sign in again
if (username.equals (user)) {
url = "/online/error.jsp";
Break
}
}
If the user is not logged in, save the user's name to the ServletContext object
Users.add (username);
}

Request.getsession (). SetAttribute ("User", username); Save the user information for later use
Response.sendredirect (URL);
}

public void DoPost (HttpServletRequest request, httpservletresponse response)
Throws Servletexception, IOException {
Doget (request, response);
}

}

Next is the servlet that the user clicks to secure exit:

Logoutservlet:

Package com.ljq.servlet;

Import java.io.IOException;
Import java.util.ArrayList;

Import javax.servlet.ServletException;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;

@SuppressWarnings ("Serial")
public class Logoutservlet extends HttpServlet {

@SuppressWarnings ("Unchecked")
public void doget (HttpServletRequest request, httpservletresponse response)
Throws Servletexception, IOException {

Get user Information
String user = (string) request.getsession (). getattribute ("user");
arraylist<string> users = (arraylist<string>) this.getservletcontext (). getattribute ("users");
for (String u:users) {
Remove this user from the ServletContext object
if (user.equals (U)) {
Users.remove (U);
Break
}
}

Set Session to invalid
Request.getsession (). invalidate ();
Response.sendredirect ("/online/login.jsp");
}

public void DoPost (HttpServletRequest request, httpservletresponse response)
Throws Servletexception, IOException {
Doget (request, response);
}

}

The last is the listener, write listener class is also very simple, as long as the corresponding listener interface and implementation of the method is not implemented. Below I write a sessionlistener, which implements the Httpsessionlistener interface:

Package com.ljq.servlet;

Import java.util.ArrayList;

Import javax.servlet.http.HttpSession;
Import javax.servlet.http.HttpSessionEvent;
Import Javax.servlet.http.HttpSessionListener;

/**
* When the user accesses a website through the network, if it is the first visit, then a session will be created on the server side of the website to save some information belonging to this user.
*
* When the session is created, it will trigger a sessioncreated event, and similarly, when the user exits normally or the user logs in without exiting and when the session life cycle ends,
*
* A sessiondestroyed event is triggered. These two events can be heard and captured by the Httpsessionlistener listener.
*
* @author Administrator
*
*/
public class Sessionlistener implements httpsessionlistener{

public void sessioncreated (Httpsessionevent event) {
SYSTEM.OUT.PRINTLN ("---session was created!---");
}

@SuppressWarnings ("Unchecked")
public void sessiondestroyed (Httpsessionevent event) {
HttpSession session = Event.getsession ();
String user = (string) session.getattribute ("User");
arraylist<string> users = (arraylist<string>) session.getservletcontext (). getattribute ("users");
for (String u:users) {
Remove this user from the ServletContext object
if (u.equals (user)) {
Users.remove (U);
Break
}
}
Set Session to invalid
Session.invalidate ();
System.out.println ("A session was destroyed!");
}

}

The work is not over, I have to configure the Web. xml file, or the server will not recognize this listener:

    <!--Listener Registration-
<listener>
<!--the path to the listener class--
<listener-class>com.ljq.servlet.SessionListener</listener-class>
</listener>

In order to test to see the results in a timely manner, I would like to configure the duration of the session, below I have the session's life cycle configured to one minute:

<session-config>   
<session-timeout>1</session-timeout>
</session-config>

OK, it's finished. This will enable the same user to have only one online

Java EE uses listeners to implement the same user can only have one online

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.