Using cookie s and filter s to write automatic login pages

Posted by AudiS2 on Sat, 11 Jan 2020 18:24:40 +0100

Flowchart of how filter works:

 

Flowchart of the automatic login page:

Many web programs do not need to log in again when they access the same web program for a certain period of time (such as a week) after their first logon, but instead go directly to the main page of the program (native only).The key to realizing this function is to identify the customer on the server side.Cookies are the simplest validation.

The code is as follows (here is dead, no database is linked): Filter page:

import java.io.IOException;
import java.util.Base64;
import java.util.Base64.Decoder;

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.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebFilter("/index.jsp")
public class LoginFilter implements Filter {

    public LoginFilter() {
    }

	public void destroy() {
	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest httpServletRequest=(HttpServletRequest)request;
		HttpServletResponse httpServletResponse=(HttpServletResponse)response;
		Cookie[] cookies = httpServletRequest.getCookies();
		boolean flag = false;
		//Check for cookie s in your browser
		if (cookies!=null&&cookies.length>0) {
			//There are cookies in the browser that are iterated through to find cookies that are logged in within a week
			for (Cookie cookie : cookies) {
				if ("loginInfo".equals(cookie.getName())) {
					//Locate and set flag bits
					flag =true;				
				}
			}
			//Filter requests based on flags Understand the use of flags
			if (flag) {
				chain.doFilter(request, response);
			}else {
				httpServletResponse.sendRedirect(httpServletRequest.getContextPath()+"/login.jsp");
			}
		}
		//There is no cookie in the browser
		else {
			httpServletResponse.sendRedirect(httpServletRequest.getContextPath()+"/login.jsp");
		}
		
	}
	public void init(FilterConfig fConfig) throws ServletException {
	}

}

Determine whether to include actions to remember user names:

import java.io.IOException;
import java.util.Base64;
import java.util.Base64.Encoder;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public LoginServlet() {
        super();
    }
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String userName = request.getParameter("userName");
		String password = request.getParameter("password");
		String auto = request.getParameter("auto");
		//Verification successfully jumped to the home page of the website
		if("tom".equals(userName)&&"123456".equals(password)){
			if("auto".equals(auto)){
				//Transcoded by base64
				String str = userName+"&"+password;
				Encoder encoder = Base64.getEncoder();
				String encodeToString = encoder.encodeToString(str.getBytes());
				Cookie cookie = new Cookie("loginInfo",encodeToString);
				cookie.setMaxAge(60);
				response.addCookie(cookie);
			}
			request.getRequestDispatcher("/index.jsp").forward(request, response);
//			response.sendRedirect("/index.jsp");
		}else{
			request.setAttribute("msg", "ERROR Incorrect username or password,Please login again");
			request.getRequestDispatcher("/login.jsp").forward(request, response);
		}
		
		
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}

 

Logon Page

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	${msg }
	<form action="login" method="post">
		 User name:<input type="text" name="userName"><br>
		 Password:<input type="password" name="password"><br>
		 Login within a week:<input type="checkbox" name="auto" value="auto">
		 <input type="submit" value="Land ">
	</form>

</body>
</html>

 

Welcome Page

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<a>Welcome</a>
</body>
</html>

Forwarding is used in LoginServlet.java, and webfilter does not filter forwarded requests by default. To filter, use this method

@WebFilter(urlPatterns= {"/index.jsp"},dispatcherTypes= {DispatcherType.FORWARD})

A 404 error will be reported if redirection is used.

This article only writes a page that uses cookies to write automatic login, without considering other security and other column issues. It is suitable for people who first contact cookies.

Topics: Java JSP Database