Java Web user login and logout method example based on Session implementation, javawebsession

Source: Internet
Author: User

Java Web user login and logout method example based on Session implementation, javawebsession

Preface

Cookie: cookie is a client technology. A program sends data of each user to the user's browser in the form of a cookie.

When a user uses a browser to access the web resources on the server, the user will carry their own data areas. In this way, the web resources process their own data.

Session: session is a server-side technology. With session technology, the server can create an exclusive session object for each user's browser at runtime. Because session is exclusive to the user's browser, therefore, when users access the web Resources of the server, they can put their own data in the session. When the user accesses other web Resources of the server again, other web resources will be stored in their sessions.
Retrieve Data for user service.

Session and Cookie:

  • Cookie is to write user data to the user's browser
  • Session technology writes user data to a session exclusively owned by the user.
  • The Session object is created by the server. developers can call the getSession method of the request object to obtain the session object.

We often use Session to store part of the user's login information to verify whether the user is online. This should be the easiest Web-side solution. This article uses SSM (Spring, SpringMVC, myBatis) the framework is the carrier to implement the specific login system.

The method is as follows:

1. the user name and password are transferred to the backend interface through the front-end. After the interface obtains the value, it performs MD5 encryption and compares it with the fields in the database, returns the status to the front-end, and the front-end redirects the Page Based on the returned value.

MD5 encryption tool

Public String EncoderByMd5 (String str) throws NoSuchAlgorithmException, UnsupportedEncodingException {// determine the calculation method MessageDigest md5 = MessageDigest. getInstance ("MD5"); BASE64Encoder base64en = new BASE64Encoder (); // encrypted String newstr = base64en. encode (md5.digest (str. getBytes ("UTF-8"); return newstr ;}

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>

Service layer implementation class

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;  }

The status information is returned to determine whether the logon is successful. If the logon succeeds, the Session is written to the user name key-value pair.

2. When other pages are accessed, how can I determine whether a user has logged on online? I use JS to retrieve the Session value to determine.

That is, get the Session value first. If the value is null or null, it indicates that the Session has not logged on before, and we will automatically redirect it to the home page. If there is a value, it indicates there is a login behavior, and the online login user is CURRENT_USER

Then, we can use the user name to call the background interface.

<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. log out

Log out, that is, clear the value in the Session, and open a logout interface in the background.

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

In this way, a user management system is implemented from login to logout. However, this is the most basic system and security is greatly affected, therefore, verification schemes similar to jwt token are useful.

Summary

The above is all the content of this article. I hope the content of this article has some reference and learning value for everyone's learning or work. If you have any questions, please leave a message to us, thank you for your support.

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.