Spring mvc step-by-step session instance details, springmvc

Source: Internet
Author: User

Spring mvc step-by-step session instance details, springmvc

Detailed description of Spring mvc step-by-step session instances

Session indicates a Session process between the server and the browser. Its information is stored on the server. In Servlet, session refers to the object of the HttpSession class. After the server creates a session, it will send the sessionid back to the client in the form of a cookie. As long as the browser of the client is not closed, the sessionid will be included for every access to the server. In this way, the session information can be obtained during each request.

Spring MVC is used as an example to illustrate how to create a step-by-step session.

1. login-Logon page

Login indicates that the user jumps to the logon page. At this time, the user can generate a sesssionid with the unique key sessionid. Save the sessionid to response. When the user logs on, the user obtains the sessionid. Because it is a step-by-step method, the user manages the sessionid in a unified manner and stores it in the Redis cache.

Public class LoginController {private static final String SESSION_ID_COOKIE = "sessionId"; @ Autowired private RedisClient client; @ RequestMapping (value = "/login/index") public ModelAndView login (HttpServletRequest request, httpServletResponse response) {ModelAndView modelAndView = new ModelAndView ("/login"); String sessionId = CookieUtils. getCookieValue (request, SESSION_ID_COOKIE); if (StringUtils. is EmptyOrNull (sessionId) {sessionId = getUniqueSessionId (); addCookie (response, SESSION_ID_COOKIE, sessionId);} // return modelAndView for other business-related information ;} // Add cookie to response private void addCookie (HttpServletResponse response, String cookieName, String cookieValue) {Cookie cookie = new Cookie (cookieName, cookieValue); cookie. setPath ("/"); cookie. setMaxAge (-1); response. addCookie (cookie);} // obtain the unique sess Ionid private String getUniqueSessionId () {String sessionId = ""; while (true) {String uuid = UUID. randomUUID (). toString (); String [] jsessionIdArray = uuid. split ("-"); StringBuilder jsessionIdBuilder = new StringBuilder (); for (String str: jsessionIdArray) {jsessionIdBuilder. append (str);} sessionId = jsessionIdBuilder. toString (); if (! RedisClient. exists (sessionId) {break ;}} return sessionId ;}}

2. authenticate-Identity Authentication/logon

The user enters the user name and password and needs to log on to the background. In this case, you can obtain the sessionid from the cookie and the sessionidvalue from redis. The session information to be saved is saved in redis with sessionidvalue as the key.

Public class LoginController {private static final String SESSION_ID_COOKIE = "sessionId"; private static final Integer REDIS_SESSION_TIME_SECONDS = 2*60*60; @ Autowired private RedisClient client; @ RequestMapping (value = "/authenticate") @ ResponseBody public ResponseInfo login (String username, String password, HttpServletRequest request) {ResponseInfo <Object> responseInfo = new ResponseInfo <Object> (); try {Account account = authenticate (username, password); saveSession (account); responseInfo. setStatus (0); responseInfo. setMessage ("success");} catch (Exceptioin e) {responseInfo. setStatus (1); responseInfo. setMessage ("the server is busy, please try again later")} return responseInfo;} // Save the session information private void saveSession (Account account Account) {String sessionId = CookieUtils. getCookieValue (request, SESSION_ID_COOKIE); redisClient. set (sessionId, account); redisClient. expire (sessionId, REDIS_SESSION_TIME_SECONDS );}}

3. logout-logout

When you select to exit the system, you need to jump to the login page, that is, the first step, and delete the session information in redis and the sessionid in the Cookie.

Public class LoginController {private static final String SESSION_ID_COOKIE = "sessionId"; @ Autowired private RedisClient client; @ RequestMapping (value = "/logout", method = RequestMethod. GET) public void logout (HttpServletRequest request, HttpServletResponse response) {// obtain the redirected location, that is, the logon page String redirectUrl = this. getLoginPageRedirectUrl (request); clearSession (request); clearSessionCookie (request, response); response. sendRedirect (redirectUrl);} // Delete the information of the session in redis private void clearSession (HttpServletRequest request) {String sessionId = CookieUtils. getCookieValue (request, SESSION_ID_COOKIE); redisClient. del (sessionId);} // Delete the sessionid private void clearSessionCookie (HttpServletRequest request, HttpServletResponse response) in the cookie {Cookie sessionCookie = CookieUtils. getCookie (request, SESSION_ID_COOKIE); sessionCookie. setMaxAge (0); response. addCookie (sessionCookie );}}

4. Get the session

You can extract the obtained session to the public Controller, so that you can inherit this class by using the session information class.

public class BaseController{  @Autowired  private RedisClient redisClient;  protected Account getAccountFromSession(HttpServletRequest request) {    String sessionCookieValue = CookieUtils.getCookieValue(request, "sessionid");    if(StringUtils.isEmptyOrNull(sessionCookieValue)) {      return null;    } else {      String accountJson = this.redisClient.get(sessionCookieValue);      Account account = null;      if(!StringUtils.isEmpty(accountJson)) {        account = (Account)JSON.parseObject(casInfoJson, Account.class);      }      return account;    }  }}

5. Summary

The basic steps for third-party session management are as follows.

  • Go to the logon page and save the sessionid to the cookie.
  • The user logs on successfully and saves the Session in redis according to the sessionid value.
  • To log out of the system, you need to clear the sessionid in the cookie and the session information of the user in redis.

After the user logs on successfully, other operations can be performed to obtain the user's session information in the request.

If you have any questions, please leave a message or go to the community on this site for discussion. Thank you for reading this article. Thank you for your support!

Related Article

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.