cookie 记住密码

上网时浏览器会有历史记录,登录某个网站时会有记住密码,这些历史记录和密码其实都是留在电脑的cookie里,你要是换一台电脑,就不会有以前的记录了。这与session不同,session的话记录留在服务器端,换了电脑,登录上去还是能看到以前的记录。
客户端记录:cookie

服务器记录:session

小例:登录时记住密码

基本结构如图

cookie 记住密码 - 丹枫白露 - 丹枫白露

Loginaction.java

package com.action;

import java.io.IOException;

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

@SuppressWarnings("serial")
public class Loginaction extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

String username=request.getParameter("username");
String password=request.getParameter("userpass");
String flag=request.getParameter("flag");

String path="/error.jsp";

if("admin".equals(username)&&"123".equals(password)){
if(flag!=null&&flag.equals("select")){
Cookie c1=new Cookie("uname",username);
Cookie c2=new Cookie("upass",password);

//设置有效时间,单位毫秒

c1.setMaxAge(60*60*60*24);
c1.setMaxAge(60*60*60*24);

response.addCookie(c1);
response.addCookie(c2);
}else{
Cookie c1=new Cookie("uname",username);
Cookie c2=new Cookie("upass",password);

c1.setMaxAge(0);
c1.setMaxAge(0);

response.addCookie(c1);
response.addCookie(c2);
}
path="/index.jsp";
}
request.getRequestDispatcher(path).forward(request,response);}

}
***********************************************************************************************************************************************************

index.xml

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>cookie</title>
</head>

<body>

<form action="login.do"method="post" >
用户:<input type="text" name="username" value="${cookie.aname.value }"><br/>
密码:<input type="password" name="userpass" value="${cookie.apsss.value}" ><br/>
记住密码:<input type="checkbox" name="flag" value="select" ${cookie.aname.value}!=null ? 'checked':''/>
<%-- ? : 表达式
不为空的话就是被选上,为空就是没被选上,不记住密码

--%>

<br/>
<input type="submit" value="登录">
</form>
</body>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值