Java Web implements automatic login using Filter

thinking

Use cookie to store account and password, use Filter to intercept, and get account and password from cookie. If the user wants to log out and no longer want to use automatic login, set the cookie's validity to 0.

Browsers can view Cookies. They can't store the plaintext of accounts and passwords directly. When using Cookies to store accounts and passwords, they need to be encrypted, and when they are taken out of Cookies, they need to be decrypted.

Every HTTP request is intercepted by Filter, and the account and password are decrypted from Cookie, which wastes time. After the account and password are decrypted from Cookie for the first time, the account and password can be placed in session domain. During the session, the account and password can be extracted directly from session without decryption.

 

 

 

Login page

<form action="loginServlet" method="post">
    //User name:<input type="text" name="user" /><br />
    //Password:<input type="password" name="pwd" /><br />
    <button type="submit">Sign in</button><br />
    ${requestScope.errorMsg}
</form>

EL expression has no null pointer exception and returns an empty string when it is not. So without errorMsg, ${requestScope.errorMsg} will not go wrong.

 

 

 

Set the login page as the project initial page

<welcome-file-list>
    <welcome-file>/login.jsp</welcome-file>
</welcome-file-list>

 

 

 

 

Servlet for processing login forms

 1 @WebServlet("/loginServlet")
 2 public class LoginServlet extends HttpServlet {
 3     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 4         String user=request.getParameter("user");
 5         String pwd=request.getParameter("pwd");
 6 
 7         //Connect to the database and check for correctness
 8         //......
 9         if (true){
10             //put to session in
11             HttpSession session = request.getSession();
12             session.setAttribute("user",user);
13             session.setAttribute("pwd","pwd");
14 
15             //Store the value after encrypting it Cookie Encryption is omitted here
16             Cookie cookie=new Cookie("autoLogin",user+"-"+pwd);
17             //Available throughout the project
18             cookie.setPath(request.getContextPath());
19             //All under this domain name address webApp All available
20             //cookie.setPath("/");
21             cookie.setMaxAge(60*60*24*7);
22             response.addCookie(cookie);
23 
24             //Redirect to the target page. request.getContextPath()What we get is the current situation. web The root directory of the application
25             response.sendRedirect(request.getContextPath()+"/index.jsp");
26             //You can't write like this. This means that the index.jsp,Not domain name/web application/index.jsp. 
27             //response.sendRedirect("/index.jsp");
28         }
29         else{
30             //Forward to the login page with additional error messages
31             request.setAttribute("errorMsg","Account name or password error");
32             request.getRequestDispatcher("/login").forward(request,response);
33         }
34 
35     }
36 
37     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
38         doPost(request,response);
39     }
40 }

 

 

 

 

home page

<h2>hello,${sessionScope.user}</h2>

 

 

 

Filter realizes automatic login

 1 @WebFilter("/*")
 2 public class HandlerFilter implements Filter {
 3     public void destroy() {
 4     }
 5 
 6     public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
 7         //Unified station coding
 8         req.setCharacterEncoding("utf-8");
 9         resp.setContentType("text/html;charset=utf-8");
10 
11         //ServletRequest Can not get session,cookie,Need to change strongly to HttpServletRequest
12         HttpServletRequest httpReq = (HttpServletRequest) req;
13 
14         //inspect session Is there user information?
15         HttpSession session = httpReq.getSession();
16         if (session.getAttribute("user")==null){
17             //Ifsession No, from Cookie Find in autoLogin. Maybe it's a second visit after the session, such as leaving the website 30 min(session The default timeout time) is then accessed again, the browser is closed, and the browser is reopened for re-access.
18             Cookie[] cookies = httpReq.getCookies();
19             //Need to be tested first cookies Whether it is null,by null When null pointer exception is reported
20             if (cookies!=null){
21                 for (Cookie cookie:cookies){
22                     if (cookie.getName().equals("autoLogin")) {
23                         //It needs to be decrypted first, which is skipped here.
24                         //......
25                         String[] userInfo=cookie.getValue().split("-");
26                         session.setAttribute("user",userInfo[0]);
27                         session.setAttribute("pwd",userInfo[1]);
28                     }
29                 }
30             }
31         }
32 
33         chain.doFilter(req, resp);
34     }
35 
36     public void init(FilterConfig config) throws ServletException {
37 
38     }
39 
40 }

 

 

 

 

Processing logout | logout | no longer uses automatic login Servlet

 1 @WebServlet("/logoutServlet")
 2 public class LogoutServlet extends HttpServlet {
 3     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 4         //from session Remove user information from
 5         HttpSession session = request.getSession();
 6         session.removeAttribute("user");
 7         session.removeAttribute("pwd");
 8 
 9         //delete Cookie,The same name overlay is used here, and it can also be retrieved by traversal, and then the validity period is set to 0.
10         Cookie cookie=new Cookie("autoLogin","");
11         cookie.setPath(request.getContextPath());
12         cookie.setMaxAge(0);
13         response.addCookie(cookie);
14     }
15 
16     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
17         doPost(request,response);
18     }
19 }

Keywords: Java Session JSP Database

Added by grungefreak on Sun, 06 Oct 2019 07:45:31 +0300