会话跟踪技术之——cookie

时间:2021-01-27 10:38:59

1.cookieForm

 <%@ 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>
<form action="setCookie.jsp" method="post">
网名:<input type="text" name="webName"/><br/>
网址:<input type="url" name="url"/><br/>
<button type="submit">提交</button>
</form>
</body>
</html>

2.setCookie

 <%@page import="java.net.URLEncoder"%>
<%@ 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>
<%
//获取从表单提交过来的数据,作为cookie的对象
String webName=request.getParameter("webName");
String url=request.getParameter("url");
//解决表单传到另一个页面乱码问题
webName=new String(webName.getBytes("ISO-8859-1"),"utf-8"); //分别创建两个cookie对象
Cookie cookie1=new Cookie("name",URLEncoder.encode(request.getParameter("webName"),"utf-8"));
Cookie cookie2=new Cookie("url",url); //分别设置Cookie的有限期
cookie1.setMaxAge(3*3600);//设置3小时
cookie2.setMaxAge(300); //在响应头部添加Cookie
response.addCookie(cookie1);
response.addCookie(cookie2);
%>
</body>
</html>

3.getCookie

 <%@page import="java.net.URLDecoder"%>
<%@ 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>
<%
Cookie[] cookie=request.getCookies();
if(cookie.length>0)
{
for(int i=0;i<cookie.length;i++)
{
String name=cookie[i].getName();
String value=cookie[i].getValue();
/* //查找某个cookie来删除
if(name.equalsIgnoreCase("name"))
{
cookie[i].setMaxAge(0);
response.addCookie(cookie[i]);
} */
//如果value的值出现乱码,则要进行解码
value=URLDecoder.decode(value, "utf-8");
out.print(name+"<br/>");
out.print(value); } } %>
</body>
</html>