Cookie overview and application of Java Web

What is Cookie

Cookie technology is a solution to keep session tracking on the client side.

II. Creation of Cookie object

Cookies can be created through the constructor of the javax.servlet.http.Cookie class.

Cookie cookie = new Cookie("username","Hum's blog");
  • The first parameter specifies the property name of the Cookie.
  • The second parameter specifies the property value.
    To create a completed kookie object, you can use the addCookie () method of the HttpServletResponse object to respond to the client browser by adding a response header.
response.addCookie(cookie);

Parameter is a Cookie object. The Cookie stored in the client is obtained through the getCookie () method of the HttpServletRequest object, which returns an array of cookies.

 Cookie [] cookies = request.getCookies();
 if(Cookie c: cookies){
		out.pritln("Attribute name"+c.getName());
		out.pritln("Attribute value"+c.getValue());
}

Cookies can be set with the setMaxAge() method for their survival time (in seconds), which is an integer indicating the number of seconds to live, a negative number indicating the temporary Cookie, and a time of 0 indicating the notification browser to delete the corresponding Cookie.

cookie.setMaxAge(7*24*60*60);//Set the cookie to live for one week. Units are seconds.

The code demonstration uses cookies to achieve permanent login.
login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<%
		String username = "";
		String password = "";
		// Get cookie
		Cookie[] cookies = request.getCookies();
		// If it is empty, stay on the page
		if(cookies == null){
			return ;
			// Get user name and password if it is not empty
		}else{
			for(int i = 0; i < cookies.length; i++){
				if("username".equals(cookies[i].getName())){
					username = cookies[i].getValue();
				}
				if("password".equals(cookies[i].getName())){
					password = cookies[i].getValue();
				}
			}
			//Verify user name and password
			if("admin".equals(username) && "123".equals(password)){
				session.setAttribute("username", username);
				session.setAttribute("password", password);
				response.sendRedirect("welcome.jsp");
			}
		}
		
	%>
 
	<form action="test" method="post">
		//User name:<input type="text" name="username" /><br /> 
		//dense&nbsp;&nbsp;&nbsp;Code:<input type="password" name="password" /><br /> 
		<input type="radio"	name="validTime" value="week" />a week 
		<input type="radio" name="validTime" value="month" />January 
		<input type="radio" name="validTime" value="default" checked="checked" />default<br /> 
		<input type="submit" value="Land" />
	</form>
</body>
</html>

CookieServlet.java

@WebServlet("/test")
public class CookieServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
 
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		resp.setContentType("text/html;charset=utf-8");
		String username = req.getParameter("username");
		String password = req.getParameter("password");
		// Get valid duration
		String validTime = req.getParameter("validTime");
		// If the verification succeeds, jump to welcome.jsp. Otherwise, jump to login.jsp.
		if ("admin".equals(username) && "123".equals(password)) {
			Cookie userCookie = new Cookie("username", username);
			Cookie pwdCookie = new Cookie("password", password);
			if ("week".equals(validTime)) {
				userCookie.setMaxAge(7 * 24 * 60 * 60);
				pwdCookie.setMaxAge(7 * 24 * 60 * 60);
			}
			if ("month".equals(validTime)) {
				userCookie.setMaxAge(30 * 24 * 60 * 60);
				pwdCookie.setMaxAge(30 * 24 * 60 * 60);
			}
			HttpSession session = req.getSession();
			session.setAttribute("username", username);
			session.setAttribute("password", password);
			resp.addCookie(userCookie);
			resp.addCookie(pwdCookie);
			resp.sendRedirect("welcome.jsp");
		} else {
			resp.sendRedirect("login.jsp");
		}
	}
 
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		this.doPost(req, resp);
	}

welcome.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	//Welcome back${username}
</body>
</html>

Keywords: JSP Session Java Attribute

Added by orlandinho on Sat, 19 Oct 2019 21:21:47 +0300