jsp是如何實現Cookie的

作者的個人分享網:分享時刻【www.itison.cn】

以下是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>
發佈了43 篇原創文章 · 獲贊 86 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章