用Cookie实现记住我功能

效果图:
在这里插入图片描述
代码:
logon.jsp:

<%@page import="org.apache.jasper.tagplugins.jstl.core.ForEach"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>




Insert title here

<%
	Cookie[] cookies = request.getCookies();
	if(cookies != null){
		for(Cookie cookie:cookies){
			if("username".equals(cookie.getName())){
				pageContext.setAttribute("username", cookie.getValue());
			}
		}
	}
	


%>




	
用户名:
记住我:

LogonServlet.java:

package text.cookie.servlet;

import java.io.IOException;

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("/logon")
public class LogonServlet extends HttpServlet{

	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		
		//1.获取请求的参数:
		String username= req.getParameter("username");
		String rem= req.getParameter("rem");

		//2.判断是否需要记住用户名
		if("on".equals(rem)) {
			//创建cookie对象,并且响应
			Cookie cookie= new Cookie("username", username);
			//设置最大的存活时间
			cookie.setMaxAge(Integer.MAX_VALUE);
			resp.addCookie(cookie);
		}else {
			Cookie cookie= new Cookie("username", "");
			cookie.setMaxAge(0);
			resp.addCookie(cookie);
		}

		//3.页面的跳转
		
	}

}

你可能感兴趣的:(Cookie,jsp,java,Servlet)