java implements automatic user login

  • 2020-05-07 19:36:24
  • OfStack

The purpose of automatic login is to help users use this page many times without having to enter the user name and password again.

Automatic login means that the user saves the user's login information, person, to the local file Cookie.

Name,value - declare new Cookie(key,value);  

Path- the default value is the path where the serlvet currently saves cookie.

If Cookie in this path: http: / / loclhost: 8080 / project abc/AServlet

The Cookie path is: http: / / loclhost project/abc

The description:

Place in http: / / loclhost/project/abc directory servlet can read the cookie values.  

If:

Save Cookie class: http: / / loclhost: 8080 / project/a/b/AServlet

Is the default path Cookie is: http: / / loclhost project/a/b

step 1: develop a login page


<c:choose>

  <c:when test="${empty sessionScope.name}">

    <form name="x" method="post" action="<c:url value='/LoginServlet'/>">

      Name:<input type="text" name="name"/><br/>

      auto:

      <input type="radio" name="auto" value="-1"> No automatic login 

      <br/>

      <input type="radio" name="auto" value="1">1 day <br/>

      <input type="radio" name="auto" value="7">1 weeks <br/>

      <input type="submit"/>

    </form>

  </c:when>

  <c:otherwise>

     You're logged in :${name}<br/>

    <a href="<c:url value='/LoginServlet'/>"> exit </a>

  </c:otherwise>

</c:choose>

step 2: successfully save cookie


public void doPost(HttpServletRequest request, HttpServletResponse response)

      throws ServletException, IOException {

    // Receive user name 

    String name = request.getParameter("name");

    String auto = request.getParameter("auto");

    // Put the user information in session

    request.getSession().setAttribute("name",name);

    // judge auto Whether it is -1

    if(!auto.equals("-1")){

      int day = Integer.parseInt(auto);//1|7

      int seconds = 60*60*24*day;

      // The statement cookie

      Cookie c = new Cookie("autoLogin",name);

      c.setMaxAge(seconds);

      c.setPath(request.getContextPath());

      // save cookie

      response.addCookie(c);

     

    }

  }

step 3: request that any page in the site should be automatically logged into

Write a filter to overwrite all url=/*. Read all cookie in doFilter. Is there a name cookie with the name autoLogin?

Always release.


public void doFilter(ServletRequest request, ServletResponse response,

      FilterChain chain) throws IOException, ServletException {

    // Read here cookie

    HttpServletRequest req = (HttpServletRequest) request;

    // Get what you have cookie

    Cookie[] cs = req.getCookies();

    if(cs!=null){

      for(Cookie c:cs){

       if(c.getName().equals("autoLogin")){// If there is an automatic login cookie

         String value = c.getValue();// The user name 

         // Login is successful 

         req.getSession().setAttribute("name", value);

         break;

       }

      }

    }

    // Whether or not the automatic login 

    chain.doFilter(request, response);

  }

part 4: configure to web.xml for all url=/*


<filter>

  <filter-name>auto</filter-name>

  <filter-class>cn.itcast.filter.AutoFilter</filter-class>

 </filter>

 <filter-mapping>

  <filter-name>auto</filter-name>

  <url-pattern>/*</url-pattern>

 </filter-mapping>

step 5: exit from development


System.err.println(" User exit ");

    // Delete the entire session

    request.getSession().invalidate();

    Cookie c = new Cookie("autoLogin", "ddd");

    c.setMaxAge(0);

    c.setPath(request.getContextPath());

    response.addCookie(c);

//   request.getSession().removeAttribute("name");

    response.sendRedirect(request.getContextPath()+"/index.jsp");

step 6: optimize the code

Since the user will also enter doFilter method of AutoFiilter when doing manual login, and read all Cookie to traverse once. This traversal is redundant for the user.

So LoginServet, url, should be included in doFiler.

And to exit also cannot automatically log in.

Additional information:

verifies that the user is logged in to


package cn.hongxin.filter;

import java.io.IOException;

import javax.servlet.Filter;

import javax.servlet.FilterChain;

import javax.servlet.FilterConfig;

import javax.servlet.ServletException;

import javax.servlet.ServletRequest;

import javax.servlet.ServletResponse;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import javax.servlet.http.HttpSession;

 

public class LoginFilter implements Filter{

  public void init(FilterConfig filterConfig) throws ServletException {

  }

  public void doFilter(ServletRequest request, ServletResponse response,

      FilterChain chain) throws IOException, ServletException {

    // will request Equivalent to htt...

    HttpServletRequest req = (HttpServletRequest) request;

    // To obtain session

    HttpSession ss = req.getSession();

    // from session To derive user

    if(ss.getAttribute("user")==null){

      System.err.println(" You haven't logged in yet ");

      req.getSession().setAttribute("msg", " Please log in first ");

      // Redirect to login 

      HttpServletResponse resp = (HttpServletResponse) response;

      resp.sendRedirect(req.getContextPath()+"/index.jsp");[W2] 

    }else{

      // release 

      chain.doFilter(request, response);

    }

  }

  public void destroy() {

  }

}

Configuration into web.xml and jsps/* considerations:


<filter>

  <filter-name>login</filter-name>

  <filter-class>cn.itcast.filter.LoginFilter</filter-class>

 </filter>

 <filter-mapping>

  <filter-name>login</filter-name>

  <url-pattern>/jsps/*</url-pattern>

  <url-pattern>/views/*</url-pattern>

 </filter-mapping>

The above is the entire content of this article, I hope to help you with your study.


Related articles: