使用cookie设置记住或自动登入登入的用户名和密码

微笑
public static void remeberMeByCookie(HttpServletRequest request,
			HttpServletResponse response) throws UnsupportedEncodingException {
		//获取页面中的登录名和密码
		String name = request.getParameter("name");
		String password = request.getParameter("password");
		//创建2个Cookie,分别用来存放登录名和密码
		//处理Cookie中存在的中文字符
		String codeName = URLEncoder.encode(name, "UTF-8");
		Cookie nameCookie = new Cookie("name",codeName);
		Cookie passwordCookie = new Cookie("password",password);
		//设置Cookie的有效路径,有效路径定义为项目的根路径
		//System.out.println("path="+request.getContextPath());
		nameCookie.setPath(request.getContextPath()+"/");
		passwordCookie.setPath(request.getContextPath()+"/");
		/**
		 * 从页面中获取记住我的复选框的值,
		 *    * 如果有值,设置Cookie的有效时长
		 *    * 如果没有值,清空Cookie的有效时长
		 * <input type="checkbox" name="remeberMe" id="remeberMe" value="yes">
		 */
		String remeberMe = request.getParameter("remeberMe");
		//设置Cookie的有效时长
		if(remeberMe!=null && remeberMe.equals("yes")){
			nameCookie.setMaxAge(7*24*60*60);
			passwordCookie.setMaxAge(7*24*60*60);
		}
		//清空Cookie的有效时长
		else{
			nameCookie.setMaxAge(0);
			passwordCookie.setMaxAge(0);
		}
		//将2个Cookie的对象存放到response对象
		response.addCookie(nameCookie);
		response.addCookie(passwordCookie);
	}

在jsp页面中进行设置:

<%
String name = "";
String password = "";
String checked = "";
Cookie [] cookies = request.getCookies();
for(int i=0;cookies!=null && i<cookies.length;i++){
	Cookie cookie = cookies[i];
	if(cookie!=null && "name".equals(cookie.getName())){
		name = URLDecoder.decode(cookie.getValue(),"UTF-8");
		checked = "checked";
	}
	if(cookie!=null && "password".equals(cookie.getName())){
		password = cookie.getValue();
	}
}
%>


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值