Java implements the user can not repeat login function

  • 2020-05-26 08:29:32
  • OfStack

An overview

A few days ago, think of this problem unintentionally, the feeling is quite practical, it is necessary to arrange 1. I wrote down a simple mode, which was not too difficult. It's actually quite easy to get your ideas straight.

In order to realize users can not log in at the same time, as long as think about the reality of sina, baidu, etc., as long as 1 landing will be another 1 to the "squeeze" down, you can know the results. Then the reverse, can form a more clear thinking. Let's talk about 1.

First of all, we have to understand what users log in to use, that is, the user online principle. This simply stores the user's object in session, which is then called from frame and referenced directly by other specific pages. The function of "squeeze down" is to make the newly generated session valid, and make the original session stored by the user invalid. So that's the general idea. So how do you do that?

To know how to do this, you must understand the process by which session stores user objects. After the user logs in, we can get the user's object user, which needs to be executed when stored in session session.setAttribute(key,value); We save the user's userId or other 1-only identifier as key and the user object as a value. This allows you to call a singleton user anytime, anywhere. The problem of user storage has been solved. What about the problem of session being abolished when the same login is used?

In fact, it is not difficult. We can use map to store the user's identity as key and the corresponding session as value, just like session, when the user logs in repeatedly, we can just take out the corresponding session and invalidate.

Now that the implementation idea is clear, after all this noise, everyone is dying to see the code, right? Here's the code:

Pre-preparation, jsp interface

The interface is very simple, just a simple login interface


<form action ="<%=request.getContextPath()%>/UserWXPServlet" method = "post"> 
   The user name š<input type = "text" name = "username"/><br/> 
   password š<input type = "text" name = "password"/><br/> 
  <input type = "submit" value =" submit "/> 
</form> 

Jump to the page after success

Welcome to: ${sessionScope.user.username}登陆!<br/>

I didn't write a failure page here, you can write your own, there's nothing to say about the failure page, right

Implementation of entity and login

The user javabean


private String username; 
private String password; 
public User() { 
} 
public User(String user, String password) { 
  super(); 
  this.username = user; 
  this.password = password; 
} 
public String getUsername() { 
  return username; 
} 
public void setUsername(String username) { 
  this.username = username; 
} 
public String getPassword() { 
  return password; 
} 
public void setPassword(String password) { 
  this.password = password; 
} 

Log on to user's service implementation method. dao and interface are not written here


public boolean dologin(User user){ 
    Properties pro = new Properties(); 
    InputStream is = UserWXPServlet.class.getClassLoader().getResourceAsStream("user_wxp.properties"); 
    String password = null; 
    System.out.println(is+"--------->"+pro); 
    if(user==null){ 
      return false;  
    } 
    try { 
      pro.load(is); 
      password = pro.getProperty(user.getUsername()); 
      if(user.getPassword()!=null&&user.getPassword().equals(password)){ 
        System.out.println(" Log in successfully "); 
        return true; 
      } 
    } catch (IOException e) { 
      e.printStackTrace(); 
    }finally{ 
      if(is!=null){ 
        try { 
          is.close(); 
        } catch (IOException e) { 
          e.printStackTrace(); 
        } 
      } 
    } 
    return false; 
  } 

Login returns true on success, false on failure.

Servlet and the corresponding logical tools class

The code that follows is the code that actually operates on the user

I have defined two classes here, one utility class and one core servlet processing class

Some common elements have been added to the tool class, such as the following code:


/** 
   *  every 1 User store 1 a session . Easy to operate!!  
   */ 
  public static Map<String, HttpSession> mapSession = new HashMap<String,HttpSession>(); 
 User exits the code (must fly to abolish session or remove Corresponding user object) : 
[java] view plain copy
public static void userLogout(String username){ 
  if(mapSession.get(username)!=null){ 
    // Get the user that needs to exit session 
    HttpSession session = mapSession.get(username); 
    // in map<username,session> To remove the user, remember to exit the user, you must remove the session To abolish or remove off user 
    mapSession.remove(username); 
    // get session Is a collection of the attributes of  
    Enumeration e = session.getAttributeNames(); 
    // Delete all attributes  
    while(e.hasMoreElements()){ 
      String sessionName = (String) e.nextElement(); 
      session.removeAttribute(sessionName); 
    } 
    // The abolition of the session 
    session.invalidate(); 
  } 
} 

The code for Servlet is as follows:


protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
  String username = request.getParameter("username"); 
  String password = request.getParameter("password"); 
  User user = new User(username, password); 
  UserService userService = new UserService(); 
  HttpSession session = request.getSession(); 
  if(userService.dologin(user)){ 
    // After successful login, insert the user into session In the  
    session.setAttribute("user", user); 
    if(cheackSession(username)){ 
      // If the session If it already exists, the user is logged out  
      DbUtil.userLogout(username); 
    } 
    // Will the new session Deposit to map<username,session> In the  
    DbUtil.mapSession.put(username, session); 
    // Successful operation, jump, best to redirect here, let others know that the login was successful  
    request.getRequestDispatcher("login").forward(request, response); 
    return ; 
  } 
  // This jumps to the failure page, which you can add if you are interested  
} 

The code of cheackSession(username) is as follows:


/** 
 *  Check to see if this is already present session 
 * @param username 
 * @return true: It already exists. Time to delete!  false : not exist  
 */ 
private boolean cheackSession(String username){ 
  HttpSession session = DbUtil.mapSession.get(username); 
  if(session!=null){ 
    return true; 
  } 
  return false; 
} 

Finally, the xml configuration for Servlet is attached


<servlet> 
  <description> 
   Used for testing   , users cannot log in again  
  </description> 
  <display-name>UserWXPServlet</display-name> 
  <servlet-name>UserWXPServlet</servlet-name> 
  <servlet-class>com.fingard.rabbit.wxp_test.Servlet.UserWXPServlet</servlet-class> 
</servlet> 
<servlet-mapping> 
  <servlet-name>UserWXPServlet</servlet-name> 
  <url-pattern>/UserWXPServlet</url-pattern> 
</servlet-mapping> 

Related articles: