jsp是如何实现Cookie的

以下是jsp实现cookie的一个简单的例子

	Cookie是存储在客户机的文本文件,它们保存了大量轨迹信息。在servlet技术基础上,JSP显然能够提供对HTTP cookie的支持。
	
通常有三个步骤来识别回头客:
1. 服务器脚本发送一系列cookie至浏览器。比如名字,年龄,ID号码等等。
2. 浏览器在本地机中存储这些信息,以备不时之需。
3 . 当下一次浏览器发送任何请求至服务器时,它会同时将这些cookie信息发送给服务器,然后服务器使用这些信息来识别用户或者干些其它事情。

这里以一个记住登陆用户名和密码的例子来测试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>
	<%
		request.setCharacterEncoding("utf-8");
		String uname = request.getParameter("uname");
		String password = request.getParameter("pwd");
		if(request.getParameter("uname").equals("liu") && request.getParameter("pwd").equals("liu")){
			Cookie c1 = new Cookie("uname",uname);
			Cookie c2 = new Cookie("password",password);
			
			// 设置cookie的生命周期
			c1.setMaxAge(10);
			c2.setMaxAge(10);
			response.addCookie(c1);
			response.addCookie(c2);
			request.getRequestDispatcher("index.jsp").forward(request, response);
		}else{
			response.sendRedirect("login.jsp");
			session.setAttribute("uname", request.getParameter("uname"));
		}
	%>
</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>
	<%
		if(session.getAttribute("uname") != null){
			out.print("登陆失败!");
		}
	%>
	
	<%
		Cookie[] cookies = request.getCookies();
		String uname = "";
		String password = "";
		for(Cookie c : cookies){
			if(c.getName().equals("uname")){
				uname = c.getValue();
			}
			if(c.getName().equals("password")){
				password = c.getValue();
			}
		}
	%>
	
	<form action="doLogin.jsp" method="post">
		<table>
			<tr>
				<td></td>
				<td><h4>请登陆用户名</h4></td>
				<td></td>
			</tr>
			<tr>
				<td>用户名:</td>
				<td><input type="text" name="uname" value="<%=uname %>"/></td>
				<td></td>
			</tr>
			<tr>
				<td>密&nbsp;码:</td>
				<td><input type="password" name="pwd" value="<%=password %>"/></td>
				<td></td>
			</tr>
			
			<tr>
				<td></td>
				<td><input type="submit" value="登陆"/><input type="reset" value="取消"/></td>
				<td></td>
			</tr>
			
		</table>
	</form>
</body>
</html>

感谢您的阅读,欢迎参观我的个人网站:闲乐小站【www.xianlewang.cn】

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值