Using filters to realize that customers only log in once per visit based on Cookie

  • 2021-09-24 22:04:25
  • OfStack

Believe that everyone in the major websites will encounter, login, login box appears next no-login/1 month no-login similar options, this article is to explain how to achieve, in this record 1, is also to do a memo collection, if there is a mistake in the text, welcome to point out

Why do you say self-login once? Because when visiting a certain page, if the first automatic login fails, you will go through the automatic login process again when you refresh the visit next time, and there will be an infinite loop.

The code example framework for this article is Spring MVC, and the following explains what you need to know to implement this function: cookies and filters

1.cookies

What is Cookies: Cookies provides a useful way for Web applications to store user-related information. For example, when a user visits your site, you can use Cookie to save user preferences or other information so that the application can retrieve previously saved information the next time the user visits your site.

Let's look at how to save cookies and how to delete cookies in 1

Save cookies


String newUserName = null;
try {
  newUserName = URLEncoder.encode(username, "UTF-8");// Transcode the user name to prevent the user name from being Chinese, cookies Save Chinese and take it out with garbled codes 
} catch (UnsupportedEncodingException e) {
  e.printStackTrace();
}
Cookie nameCookie = new Cookie("username", newUserName);
String pwdMd5Cook = MD5Util.MD5(Pwd);
Cookie pwdCookie = new Cookie("pwd", pwdMd5Cook);//  Save the encrypted password 
nameCookie.setMaxAge(60 * 60 * 24 * 365);//  User name saving 1 Year 
pwdCookie.setMaxAge(60 * 60 * 24 * 30);//  Password saving 30 Days 
//  Send Cookie Information to browser 
response.addCookie(nameCookie);
response.addCookie(pwdCookie);

Delete cookies, deletion is very simple, but it is worth noting, delete cookies, and save cookies1 must be in the same control layer, otherwise you will not find the saved cookies, resulting in deletion


Cookie cookie = new Cookie("pwd", null);
cookie.setMaxAge(0);//  Delete password cookie
response.addCookie(cookie);

2. Filter-Filter

Filter is also called filter, which is the most practical technology in Servlet technology. Web developers intercept all web resources managed by web server through Filter technology, such as Jsp, Servlet, static picture files or static html files, so as to realize some special functions. For example, URL level access control, filtering sensitive vocabulary, compressing response information and other advanced functions.

Implementation method: Inherit Filter interface and implement its doFilter method. Register the written filter class in the web. xml file and set the resources it can block


<filter> Specify 1 Filters. 
<filter-name> Used to specify for the filter 1 The content of this element cannot be empty. 
<filter-class> Element is used to specify the complete qualified class name of the filter. 
<init-param> Element is used to specify initialization parameters for the filter, and its child elements <param-name> Specifies the name of the parameter, <param-value> Specifies the value of the parameter. 
 In the filter, you can use the FilterConfig Interface object to access the initialization parameters. 
<filter-mapping> Element is used to set the 1 A  Filter  Resources that are responsible for intercepting. 1 A Filter Intercepted resources can be specified in two ways: Servlet  Name and request path for resource access 
<filter-name> Child element is used to set the filter The registered name of the. The value must be in the <filter> The name of the filter declared in the element 
<url-pattern> Settings  filter  Intercepted request path ( Filter-associated URL Style )
<servlet-name> Specifies that the filter intercepts Servlet Name. 
<filter>
  <filter-name>suicaiFilter</filter-name>
  <filter-class>com.suicai.filter.suicaiFilter</filter-class>
</filter>
<filter-mapping>
  <filter-name>suicaiFilter</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

Let's look at the actual application code:


public class suicaiFilter implements Filter {
  @Override
  public void destroy() {
  }
  @Override
  public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException {
    HttpServletRequest req=(HttpServletRequest)request;
    HttpServletResponse res=(HttpServletResponse)response;
    HttpSession session = req.getSession();
    String requestURI = req.getRequestURI();
    String param = req.getQueryString();
    String url = req.getServletPath();
    if(param!=null){
      url = url+"?"+param;
    }
    if(requestURI.contains("js") || requestURI.contains("css") || requestURI.contains("images")){
      // Non-filtering css,js,images Static resources such as 
      chain.doFilter(request, response);
    }else if(requestURI.contains("/info/")||requestURI.contains("/gys/")){
      // Filter the front desk access page, and log in automatically with the front desk personal center (supplier background) 1 If the login is unsuccessful, no operation will be carried out. If the login of personal center is unsuccessful, jump to the login page 
      ProviderInfo providerInfo = (ProviderInfo) session.getAttribute("providerInfo_gys");
      String IsAutomaticLogin = (String) session.getAttribute("IsAutomaticLogin");// Whether you have gone through the automatic login process identification 
      if(requestURI.contains("/info/") && !requestURI.contains("/login")){
        // If you don't need to log in to access the portal (except login), just try to log in 1 If it is unsuccessful, no action will be taken 
        if(providerInfo==null && IsAutomaticLogin == null){
          req.getSession().setAttribute("goURL", url);
          res.sendRedirect(req.getContextPath() + "/common/automaticLogin");
        }else if(providerInfo==null && IsAutomaticLogin != null ){
          chain.doFilter(request, response);
        }else{
          chain.doFilter(request, response);
        }
      }else if(requestURI.contains("/gys/")){// Visit the personal center, from logging in 1 Unsuccessful jump to login page 
        if(providerInfo==null && IsAutomaticLogin == null){
          req.getSession().setAttribute("goURL", url);
          res.sendRedirect(req.getContextPath() + "/common/automaticLogin");
        }else if(providerInfo==null && IsAutomaticLogin != null ){
          session.setAttribute("redirectUrl", url);
          res.sendRedirect(req.getContextPath() + "/login.jsp?redirectUrl="+url);
        }else{
          chain.doFilter(request, response);
        }
      }else{
        chain.doFilter(request, response);
      }
    }else{
      // Non-filtering 
      chain.doFilter(request, response);
    }
  }
  @Override
  public void init(FilterConfig arg0) throws ServletException {
  }
}

From the code, we can see that we need an ID (IsAutomaticLogin) that has been automatically logged in, and this ID is saved when we go through automatic login (whether it is successful or not)

3. Combined with the knowledge provided above, the following is the overall code display. If you find something wrong, you are welcome to point out it


@Controller
@RequestMapping("/common")
public class CommonController{
  /**
   *  Automatic login method 
   * @param request
   * @param response
   * @param username
   * @param pwd
   * @param ProviderInfo  Vendor account information model
   * @return
   */
  @RequestMapping("/automaticLogin")
  public String automaticLogin(HttpServletRequest request,ServletResponse response,@CookieValue(value = "username", required = false) String username,@CookieValue(value = "pwd", required = false) String pwd,ProviderInfo ProviderInfo) {
    //  Save the link before requirement login 
    String goURL = (String) session.getAttribute("goURL");
    if (username == null) {//cookies There is no user name in, so there is definitely no need to log in automatically 
      session.setAttribute("IsAutomaticLogin", "0");
      return "redirect:" + goURL;
    } else {
      try {
        username = URLDecoder.decode(username, "UTF-8");// Escape, prevent Chinese 
      } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
      }
    }
    // cookie Failure  session1 Is set to blank, because when logging in, 1 The user name will be saved in the cookie Medium 
    if ("".equals(username) || username == null) {//  Use session Can't log in, don't do anything , No longer enter this method 
      session.setAttribute("IsAutomaticLogin", "0");
      return "redirect:" + goURL;
    } else {
      // cookie There is no password in, judge session Is not empty, if it is empty, it means that there is no login, if it is not empty, it means that the user chose not to remember the password to log in (so cookie There is no password in) 
      if ("".equals(pwd) || pwd == null) {
        ProviderInfo customer1 = (ProviderInfo) session.getAttribute("providerInfo_gys");
        if (customer1 == null) {//  Use session Can't log in, don't do anything , No longer enter this method 
          session.setAttribute("IsAutomaticLogin", "0");
          return "redirect:" + goURL;
        } else {
          //  Already logged in , No more access to this method 
          return "redirect:" + goURL;
        }
      } else {
        // cookie There is a password in, judge session Is not empty. If it is empty, it means no login. If it is not empty, it means no login , Explain that you are logged in 
        ProviderInfo customer1 = (ProviderInfo) session.getAttribute("providerInfo_gys");
        if (customer1 == null) {//  There is currently no login, call cookies Login with the user name and password in 
          //  Carry out automatic login operation and return to the original page after successful login 
          ProviderInfo customer3 = ValidateDate(username);
          customer3.setPwd(pwd);
          customer3.setAccountType(6);
          ProviderInfo customer2 = infoService.login(customer3);// Call the login method 
          if (customer2 == null) {//  Automatic login failed , No more access to this method 
            session.setAttribute("IsAutomaticLogin", "0");
            return "redirect:" + goURL;
          } else {
            //  Login successfully saves customer information to session
            session.setAttribute("providerInfo_gys",customer2);
            return "redirect:" + goURL;
          }
        } else {
          return "redirect:" + goURL;
        }
      }
    }
  }
  /**
   *  User login 
   * @param request
   * @param response
   * @param cus
   * @return
   */
  @RequestMapping("/UserLogin")
  @ResponseBody
  public Map<String, Object> goLogin(HttpServletRequest request,HttpServletResponse response,@ModelAttribute("ProviderInfo") ProviderInfo cus) {
    /* Omission 1 Some logical judgments */
    cus.setPwd(MD5Util.MD5(Pwd));
    ProviderInfo providerInfo = infoService.login(cus);
    Map<String, Cookie> cookieMap = new HashMap<String, Cookie>();
    if (providerInfo == null) {
      //  Log in failed , Jump to the landing page again 
      map.put("error", " Password error ");
      return map;
    }else{
      String newUserName = null;
      if (remember_me.equals("1")) {//  Have a choice 1 Month login-free 
        try {
          newUserName = URLEncoder.encode(username, "UTF-8");
        } catch (UnsupportedEncodingException e) {
          e.printStackTrace();
        }
        Cookie nameCookie = new Cookie("username", newUserName);
        String pwdMd5Cook = MD5Util.MD5(Pwd);
        Cookie pwdCookie = new Cookie("pwd", pwdMd5Cook);//  Save the encrypted password +"create"
        nameCookie.setMaxAge(60 * 60 * 24 * 365);//  User name saving 1 Year 
        pwdCookie.setMaxAge(60 * 60 * 24 * 30);//  Password saving 30 Days 
        //  Send Cookie Information to browser 
        response.addCookie(nameCookie);
        response.addCookie(pwdCookie);
        session.setAttribute("IsAutomaticLogin",null);
      }else{// No selection, delete the password when automatic logon may have been selected last time 
        Cookie[] cookies = request.getCookies();
        if (null != cookies) {
          for (Cookie cookie : cookies) {
            cookieMap.put(cookie.getName(), cookie);
          }
        }
        if (cookies != null) {
          for (int i = 0; i < cookies.length; i++) {
            if (cookieMap.containsKey("pwd")) {
              Cookie cookie = new Cookie("pwd", null);
              cookie.setMaxAge(0);//  Delete password cookie
              response.addCookie(cookie);
            }
          }
        }
      }
      //  Successful login , Save the current user Information, save customer information to session
      map.put("ProviderInfo", providerInfo);
      map.put("goURL", session.getAttribute("goURL"));
      session.setAttribute("providerInfo_gys", providerInfo);
      return map;
    }else {
      map.put("error", " The vendor account number does not exist ");
      return map;
    }
  }
  /**
   *  Logoff 
   * @return
   */
  @RequestMapping("/logout")
  public String logout(HttpServletResponse response) {
    Map<String, Cookie> cookieMap = new HashMap<String, Cookie>();
    Cookie[] cookies = request.getCookies();
    if (null != cookies) {
      for (Cookie cookie : cookies) {
        cookieMap.put(cookie.getName(), cookie);
      }
    }
    if (cookies != null) {
      for (int i = 0; i < cookies.length; i++) {
        if (cookieMap.containsKey("pwd")) {
          Cookie cookie = new Cookie("pwd", null);
          cookie.setMaxAge(0);//  Delete password cookie
          response.addCookie(cookie);
        }
      }
    }
    session.setAttribute("providerInfo_gys", null);
    return "/index";
  }
}

Related articles: