编写cookie和session

编写cookie

1.创建cookie对象

//创建cookie对象
Cookie usernameCookie=new Cookie("username", username);

2.设置最长生命周期,单位毫秒,不设置,浏览器关闭就会消失

usernameCookie.setMaxAge(1000*60*60);

这里设置为1个小时,单位是1ms

3.设置路径

usernameCookie.setPath("/");

配置的路径是相对路径

4.通过响应对象,将cookie写入浏览器

resp.addCookie(usernameCookie);

ui段获取cookie

		Cookie[] cookies = req.getCookies();
		String username="";
		String password="";
		for (Cookie cookie : cookies) {
			if (cookie!=null&&cookie.getName().equals("username")) {
				username=cookie.getValue();				
			}
			if (cookie!=null&&cookie.getName().equals("password")) {
				password=cookie.getValue();				
			}
		}

直接在静态网页的html加入定义的字符串就行了,例如:

writer.println("用户名:<input name=\"username\"  value=\""+username+"\"  type=\"text\"><br/>");
writer.println("密码:<input name=\"password\"  value=\""+password+"\"  type=\"password\"><br/>");

编写session

1.获得请求session的对象

HttpSession session=req.getSession();
session.setAttribute("username", username);
session.setAttribute("password", password);

2.调用session

HttpSession session=req.getSession();
String username=(String) session.getAttribute("username");
String password=(String) session.getAttribute("password");

注意:如果用eclipse编写的话,可能要去tomcat下载一个apache-tomcat-8.5.45-src.zip的压缩包。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值