JavaWeb user login and logout method example based on Session implementation

  • 2020-12-10 00:41:58
  • OfStack

preface

Cookie:cookie is a client-side technology in which programs write each user's data in cookie to the user's browser.

When the user uses the browser to access the web resources in the server, they take their respective data areas with them, so that the web resources process their own data.

Session: session is server side technology, using session technology, server at run time for each one of the user's browser to create the exclusive session object, because session be exclusive to the user's browser, so the user is in when access server web resources, can put their data on session, when a user to access the server again in other web resources, other web resources from the user's respective session again
Take the data and serve it to the user.

Key differences between Session and Cookie:

Cookie is the browser that writes the user's data to the user Session technology writes the user's data to the user's exclusive session. The Session object is created by the server, and the developer can call the getSession method of the request object to get the session object.

We often use Session to store part of the login information of the user to verify whether the user is online, which should be the easiest to implement one of the Web terminal schemes. This paper takes SSM (Spring, SpringMVC, myBatis) framework as the carrier to specifically implement this login system.

The methods are as follows:

1. Pass the user name and password to the back-end interface through the front end. After the interface gets the value, it encrypts MD5, compares it with the fields in the database, returns the status to the front end, and the front end jumps to the page according to the return value.

MD5 encryption tool class


public String EncoderByMd5(String str) throws NoSuchAlgorithmException, UnsupportedEncodingException{
    // Determination of calculation method 
    MessageDigest md5=MessageDigest.getInstance("MD5");
    BASE64Encoder base64en = new BASE64Encoder();
    // The encrypted string 
    String newstr=base64en.encode(md5.digest(str.getBytes("utf-8")));
    return newstr;
  }

The DAO layer and Mapper


<select id="valiteUser" parameterType="java.lang.String" resultType="com.heitian.ssm.model.Userinfo">
    SELECT password FROM t_user
    WHERE username = #{username}
</select>

The Service layer implements classes


public String valiteUser(Userinfo userinfo) {
    try{
      Userinfo userdemo=userDao.valiteUser(EncoderByMd5(userinfo.getUsername()));
      if(userinfo.getPassword().equals(userdemo.getPassword())){
        return "pass";
      }
    }catch (Exception e){
      e.printStackTrace();
      return "error";
    }
    return "refuse";
  }

Controller layer


  @ResponseBody
  @RequestMapping("/loginUser")
  public HashMap<String,Object> loginUser(HttpServletRequest request, Userinfo userinfo){
    HashMap<String,Object> result=new HashMap<String, Object>();
    HttpSession session = request.getSession();
    System.out.println("login fail");
    String status=userService.valiteUser(userinfo);
    if(status.equals("pass")){
      session.setAttribute("CURRENT_USER",userinfo.getUsername());
      result.put("status","pass");
    }else{
      if(status.equals("refuse")){
        result.put("status","refuse");
      }else {
        result.put("status","error");
      }
    }
    return result;
  }

Determine whether the login was successful by returning status information, and if so, write the user name key-value pair in Session.

2. When other pages visit, how to determine whether a user is logged in or not? I use JS to get the value of Session to determine.

That is: first, get the value of Session. If the value is empty or null, it means that there is no login behavior before this session, so we automatically redirect it to the homepage. If there is a value, it means that there is login behavior, and the logged in user is CURRENT_USER

The value taken out, at this time we use the username to call the background interface can be.


<script language="JavaScript">
  $(document).ready(function(){
      var myName="<%=session.getAttribute("CURRENT_USER")%>";
      var projiectid1= "<%=request.getAttribute("projectid")%>";
      if(myName=="null"){
        window.location.href="/page/toindex" rel="external nofollow" ;
      }
</script>

3. User logout

Logout, that is, the value in Session can be cleared, and one logout interface can be opened by the background.


@RequestMapping("/quitUser")
  public String quitUser(HttpServletRequest request){
    HttpSession session = request.getSession();
    session.removeAttribute("CURRENT_USER");
    return "index";
  } 

This makes for a log-in to logout user management system, but it is a basic system and security is a big problem, so authentication schemes like JWT TOKEN are useful.

conclusion


Related articles: