web中的Cookie、session、application

Cookie:

注意

1.临时以文件的形式将数据存储在用户的计算机上只能记录key-value对,在浏览器temp文件夹;
2.最常见是存用户名, 作用:免登陆,还可以存搜索记录…
3.不存密码,技术上可行,md5加密,但不这么干
4.透明,所有网站都可以看得到,淘宝的cookie,京东也可以看到

使用

验证成功时

if(c>0){
	//解决中文乱码问题
	String cu_nsme_utf8 = URLEncoder.encode(cu_name,"utf-8");
	Cookie cookie = new Cookie("cu_name",cu_name_utf8);
	cookie.setMaxAge(600);
	response.addCookie(cookie);
	保存cookie是浏览器的动作,需放在跳转之前
	
	response.sendRedirect("/web02/welcome1_1.jsp?cu_name="+cu_name);
}

在登录页面

String cu_name="";
Cookie[] cookies = request.getCookies();
if(cookies!=null&&cookies.length>0){
	for(Cookie c:cookies){
		if("cu_name".equals(c.getName())){
			String cu_name_utf8=c.getValue();
			//解码,避免中文乱码
			cu_name = URLDecoder.decode(cu_name_utf8,"utf-8");
		}
	}
}

登出(删除Cookie)

Cookie cookie = new Cookie("cu_name","");
cookie.setMaxAge(0);    cookie保存的最大时间,单位是秒
response.addCookie(cookie);
response.sendRedirect("/web02/test1.jsp");

session

sessionid:
在服务器接收到第一次请求时,建立新的会话,服务器为这次会话创建一个整个服务器都唯一的sessionid

注意

1.文件存在服务器端
2.浏览器重启,session消失,新会话创建,创建新的sessionid
3.服务器重启,sessionid消失;
4.cookie存在客户端,只能存String类型,session存在服务器端,能运行java,可以存Object;

使用

验证成功时

if(c>0){
		session.setAttribute("cu_name",cu_name);
		response.sendRedirect("/web02/welcome1_1.jsp?cu_name="+cu_name);
}

取值(注意数据类型转换

<%=(String)session.getAttribute("cu_name") %>

application

注意
1.能不用就不用

使用

<%
int count=10000000;
if(application.getAttribute("count")==null){
	application.setAttribute("count",10000000);
}else{
	int c = (int) application.getAttribute("count");
	c+=new Random().nextInt(10000);
	count=c;
	application.setAttribute("count",c);
}
%>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值