jsp 使用cookie保存用户名和密码

<%@ 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>
	<%!
		String uname;
		String upwd;
	%>
	<%
		Cookie[] cookies=request.getCookies();//获取所有的cookies
		for(Cookie cookie:cookies){
			//找到uname的cookie
			if(cookie.getName().equals("uname")){
				uname=cookie.getValue();
			}
			//找到upwd的cookie
			if(cookie.getName().equals("upwd")){
				upwd=cookie.getValue();
			}
		}
	%>
<form action="check.jsp" method="post">
	用户名:<input type="text" name="uname" value="<%=(uname==null?"":uname)%>"><br/>//该框中的值是保存在value中的
	密码:<input type="text" name="upwd" value="<%=(upwd==null?"":upwd)%>"><br/>
	<input type="submit" value="登录"><br/>
</form>


</body>
</html>
<%@ 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>
<%
	request.setCharacterEncoding("utf-8");
	String name=request.getParameter("uname");
	String pwd=request.getParameter("upwd");
	
	//将用户名加入到cookie
	Cookie cookie1=new Cookie("uname",name);//建议cookie中只保存英文和数字否则涉及到编码问题
	Cookie cookie2=new Cookie("upwd",pwd);
	response.addCookie(cookie1);
	response.addCookie(cookie2);
	response.sendRedirect("result.jsp");//cookies也随之返回到了客户端所以在login界面可以用到
	
%>

</body>
</html>

猜你喜欢

转载自blog.csdn.net/qq_41648092/article/details/86560610