使用cookie
Cookie是存储在客户机的文本文件,它们保存了大量轨迹信息。在servlet技术基础上,JSP显然能够提供对HTTP cookie的支持。
通常有三个步骤来识别回头客:
- 服务器脚本发送一系列cookie至浏览器。比如名字,年龄,ID号码等等。
- 浏览器在本地机中存储这些信息,以备不时之需。
- 当下一次浏览器发送任何请求至服务器时,它会同时将这些cookie信息发送给服务器,然后服务器使用这些信息来识别用户或者干些其它事情
简单示例:
<%@ page import="java.net.URLEncoder" %><%--
Created by IntelliJ IDEA.
User: vina
Date: 18-4-6
Time: 上午8:59
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Test Cookie</title>
</head>
<body>
<%
String str = URLEncoder.encode(request.getParameter("name"), "utf-8");
Cookie name = new Cookie("name", str);
Cookie url = new Cookie("url", request.getParameter("url"));
name.setMaxAge(60*60*24);
url.setMaxAge(60*60*24);
response.addCookie(name);
response.addCookie(url);
%>
<ul>
<li>
<p>网站名: <%=request.getParameter("name")%></p>
</li>
<li>
<p>网址: <%=request.getParameter("url")%></p>
</li>
<li>
<p><a href="TestCookieGet.jsp">Cookie测试</a></p>
</li>
</ul>
</body>
</html>
将上述代码保存为TestCookie.jsp
<%@ page import="java.net.URLDecoder" %><%--
Created by IntelliJ IDEA.
User: vina
Date: 18-4-6
Time: 上午9:15
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%
Cookie cookie = null;
Cookie[] cookies = null;
cookies = request.getCookies();
if(cookies != null){
out.println("<h1>查找cookie<h1>");
for(int i = 0; i < cookies.length; i++){
cookie = cookies[i];
out.print("参数名:" + cookie.getName());
out.print("<br>");
out.print("参数值:" + URLDecoder.decode(cookie.getValue(), "utf-8"));
out.print("<br>");
}
}
else
out.print("<h1>没有发现cookie<h1>");
%>
</body>
</html>
将上述代码保存为TestCookieGet.jsp
以上就是JSP中cookie的简单用法