十二月 20, 2015 19:59:17
处理cookie
1.Http协议的无连接性要求一种保存C/S间状态的机制
2.Coolie:保存到客户端的一个文本文件,与特定客户无关
3.Cookie以“名--值”对的形式保存数据
4.创建Cookie:new Cookie(name,value)
5.可以使用Cookie 的serXXX方法来设定一些相应的值
5.1 setName(String name)/getName()
5.2 setValue(String value)/getValue()
5.3 setMaxAge(int age)/getMaxAge()
5.4 利用HttpServletResponse的addCookie(Cookie)方法将它设置到客户端
5.5 利用HttpServletRequest的getCookies()方法来读取客户端的所有的cookie。
一、cookie原理:
基本原理:
1.服务器可以向客户端写的内容,
2.只能是文本文档
3.客户端可以阻止不让写
4.只能拿自己的webapp写的东西(一个浏览器的标记)
是服务器在本地写的内容,可以进行阻止写入cookie,
在internet选项-->隐私-->高(阻止所有cookie)
cookie在本地的地址:
C盘.....C:\Documents and Settings\Administrator\Cookies
Documents and Settings\Administrator\Cookies
server向client端的cookies;
1.如果设置周期时,写在本地;
2.未设置或者为-1时,是写在client端的内存里;关掉本窗口,就没了。
5.cookie分为两种
属于窗口/子窗口
属于文本
6.一个servlet/jsp设置的cookies能够被同一个路径下面或者子路径下面的servlet/jsp读到(路径=url)
(路径!=真实文件路径)
二、cookie代码案例
SetCookies.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 设置Cookie到客户端
* @author jukey
*
*/
public class SetCookies extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 向客户端写入Cookie,共6个
for(int i = 0; i < 3; i++) {
// 3个没设置时间的Cookie,属于本窗口及其子窗口
Cookie cookie = new Cookie("Session-Cookie-" + i, "Cookie-Value-S" + i);
response.addCookie(cookie);
// 以下3个Cookie设置了时间(3600秒,1小时,属于文本,别的窗口也可以访问到这些Cookie
cookie = new Cookie("Persistent-Cookie-" + i, "Cookie-Value-P" + i);
cookie.setMaxAge(3600);
response.addCookie(cookie);
}
response.setContentType("text/html;charset=gb2312");
PrintWriter out = response.getWriter();
String title = "Setting Cookies";
out.println("<html><head><title>设置Cookie</title></head>"
+ "<body>" + title + "<br>"
+ "There are six cookies associates with this page.<br>"
+ "to see them,visit the <a href=\"ShowCookies\">\n"
+ "<code>ShowCookies</code> servlet</a>"
+ "</body></html>");
}
}
ShowCookies
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 读取客户端的Cookies
*/
public class ShowCookies extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=gb2312");
PrintWriter pw = response.getWriter();
String title = "Active Cookies";
pw.println("init");
pw.println("<html><head><title>读取客户端</title></head>"
+ title
+ "\n" + "<table border=1 align=center>\n"
+ "<TH>Cookie Name<TH>Cookie Value" + "<br>");
// 读取客户端的所Cookie
Cookie[] cookies = request.getCookies();
if(cookies != null) {
Cookie cookie;
for(int i = 0; i < cookies.length; i++) {
cookie = cookies[i];
pw.println("<tr>\n" + "<td>" + cookie.getName() +"</td>\n"
+ "<td>" + cookie.getValue() +"</td></tr>\n");
}
}
pw.println("</table>\n<body><html>");
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <servlet> <servlet-name>HelloServlet</servlet-name> <servlet-class>HelloServlet</servlet-class> </servlet> <servlet> <servlet-name>ServletLifeCycle</servlet-name> <servlet-class>ServletLifeCycle</servlet-class> </servlet> <servlet> <servlet-name>ThreeParams</servlet-name> <servlet-class>ThreeParams</servlet-class> </servlet> <servlet> <servlet-name>ShowParameters</servlet-name> <servlet-class>ShowParameters</servlet-class> </servlet> <servlet> <description>This is the description of my J2EE component</description> <display-name>This is the display name of my J2EE component</display-name> <servlet-name>SetCookies</servlet-name> <servlet-class>SetCookies</servlet-class> </servlet> <servlet> <description>This is the description of my J2EE component</description> <display-name>This is the display name of my J2EE component</display-name> <servlet-name>ShowCookies</servlet-name> <servlet-class>ShowCookies</servlet-class> </servlet> <servlet-mapping> <servlet-name>HelloServlet</servlet-name> <url-pattern>/httpServlet</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>ServletLifeCycle</servlet-name> <url-pattern>/ServletLifeCycle</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>ThreeParams</servlet-name> <url-pattern>/ThreeParams</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>ShowParameters</servlet-name> <url-pattern>/servlet/ShowParameters</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>SetCookies</servlet-name> <url-pattern>/servlet/SetCookies</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>ShowCookies</servlet-name> <url-pattern>/servlet/ShowCookies</url-pattern> </servlet-mapping> </web-app>
结果:
本地cookies存在的
Persistent-Cookie-0
Cookie-Value-P0
localhost/TestServlet01/servlet/
1536
1530043264
30489391
4193558928
30489382
*
Persistent-Cookie-1
Cookie-Value-P1
localhost/TestServlet01/servlet/
1536
1530043264
30489391
4193558928
30489382
*
Persistent-Cookie-2
Cookie-Value-P2
localhost/TestServlet01/servlet/
1536
1530043264
30489391
4193558928
30489382
*
三、会话跟踪 Session
3.1 在某段时间一连串客户端与服务器端的交易
3.2 在Jsp/Servlet中,如果浏览器不支持Cookie,可以通过URL重写来实现,就试讲一些额外数据追加到表示会话的每个URL末尾,
服务器在该标识符与其存储的有关的该会话的数据之间建立关联。
如: hello.jsp?jsessionid=1234
3.3 可以通过程序来终止一个会话。如果客户端在一定时间内没有操作,服务器会自动终止会话。
3.3 通过HttpSession来读写Session
规则:
1.如果浏览器支持Cookie,创建Session的还好会把SessionID保存在Cookie里
2.如果不支持Cookie,必须自己变成使用URL重写的方式实现Session
2.1 response.encodeURL()
转码
URL后面加入SessionId
2.2Session不像Cookie拥有路径访问的问题
同一个application下的servet/jsp可以共享同一个session,前提是同一客户端窗口。
session是和窗口关联起来的,窗口关了这个sessionid就没了
HttpServletRequest中的Session管理方法
1.getRequestSessionId():
返回随客户端请求到来的会话ID。可能与当前的会话ID相同,也可能不同。
2.getSession(boolean isNew): 如果会话已存在一个HttpSession,如果不存在并且isNew()为true,则会创建一个HttpSession。
3.isRequestedSessionIdFromCookie():当前的session ID如果是从cookie获得,为true。
4.isRequestedSessionIdValid(): 如果客户端的会话ID代表的是有效会话,则返回true。否则(比如,会话国企或根本不存在),返回false。
5.HttpSession的常用方法:
5.1getAtrributeNames()/getAttribute()
5.2getCreateTime()
5.3getId()
5.4 getMaxInactiveInterval()
5.5invalidate()
5.6 isNew()
5.7 setAttribuye()
5.8 setMaxInactivateInterval()
refresh后jsessionid=45F4C3391CB26DAE6B28C104B6571A12
out.println("<a href=" + response.encodeURL("SessionInfoServlet") + ">refresh</a>");
http://localhost:8080/TestServlet01/servlet/SessionInfoServlet;jsessionid=45F4C3391CB26DAE6B28C104B6571A12
代码案例
import java.io.IOException; import java.io.PrintWriter; import java.util.Date; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; /** * 演示Servlet API中的session管理机制(常用方法) * @author jukey * */ public class SessionInfoServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Returns the current session associated with this request, or if the request does not have a session, creates one. HttpSession mySession = request.getSession(true); response.setContentType("text/html"); PrintWriter out = response.getWriter(); String title = "Session Info Servlet"; out.println("<html>"); out.println("<head>"); out.println("<title>Session Info Servlet</title>"); out.println("</head>"); out.println("<body>"); out.println("<h3>Session Infomation</h3>"); // Returns true if the client does not yet know about the session or if the client chooses not to join the session. out.println("New Session:" + mySession.isNew() + "<br>"); // Returns a string containing the unique identifier assigned to this session. out.println("Session Id:" + mySession.getId() + "<br>"); // Returns the time when this session was created, measured in milliseconds since midnight January 1, 1970 GMT. out.println("Session Create Time:" + new Date(mySession.getCreationTime()) + "<br>"); out.println("Session Last Access Time:" + new Date(mySession.getLastAccessedTime()) + "<br>"); out.println("<h3>Request Infomation</h3>"); // Returns the session ID specified by the client. out.println("Session Id From Request:" + request.getRequestedSessionId() + "<br>"); // Checks whether the requested session ID came in as a cookie. out.println("Session Id Via Cookie:" + request.isRequestedSessionIdFromCookie() + "<br>"); // Checks whether the requested session ID came in as part of the request URL. out.println("Session Id Via URL:" + request.isRequestedSessionIdFromURL() + "<br>"); // Checks whether the requested session ID is still valid. out.println("Valid Session Id:" + request.isRequestedSessionIdValid() + "<br>"); out.println("<a href=" + response.encodeURL("SessionInfoServlet") + ">refresh</a>"); out.println("</body></html>"); out.close(); } }
ShowSession
import java.io.IOException; import java.io.PrintWriter; import java.util.Date; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; /** * Session追踪 * 如果浏览器支持Cookie,创建Session的时候会把SessionId保存在Cookie中 * 否则必须自己编程使用URL重写的方式实现Session:response.encodeURL() * @author jukey * */ public class ShowSession extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=gb2312"); PrintWriter out = response.getWriter(); String str = "Session Tracking Example"; String heading; // 如果会话已经存在,则返回一个HttpSession;否则创建一个新的 HttpSession session = request.getSession(true); // 从当前session中读取属性accessCount的值 Integer accessCount = (Integer)session.getAttribute("accessCount"); if(accessCount == null) { accessCount = new Integer(0); heading = "Welcome newUser"; } else { heading = "Welcome Back"; accessCount = new Integer(accessCount.intValue() + 1); } // 向当前session中插入键(key,属性)值(value)对 // Binds an object to this session, using the name specified. session.setAttribute("accessCount", accessCount); out.println("<html><head><title>Session追踪</title></head>" + "<body>" + heading + "<br>" + "<h2>Information on Your Session</h2><br>" + "\n" + "<table border=1 align=center>\n" + "<TH>Info Type<TH>Value" + "<br>" + "<tr>\n" + "<td>ID</td>\n" + "<td>" + session.getId() +"</td></tr>\n" + "<tr>\n" + "<td>CreatTime</td>\n" + "<td>" + new Date(session.getCreationTime()) +"</td></tr>\n" + "<tr>\n" + "<td>LastAccessTime</td>\n" + "<td>" + new Date(session.getLastAccessedTime()) +"</td></tr>\n" + "<tr>\n" + "<td>Number of Access</td>\n" + "<td>" + accessCount +"</td></tr>\n" + "</body></html>"); } }
四、Application
4.1 用于保存整个WebApplication的生命周期内都可以访问的数据
4.2 在API中表现为ServletContext
4.3通过HttpServlet的getServletContext方法可以拿到
4.4通过ServletContext的get/setAttribute方法取得/设置相关属性
http://localhost:8080/TestServlet01/servlet/TestServletContext
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Application测试
* 用于保存整个web应用的生命周期内都可以访问的数据
* 可供多个不同窗口访问,可作为某一页面被总共访问次数的计数器(比如网站首页的访问量)
* @author jukey
*
*/
public class TestServletContext extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=gb2312");
PrintWriter out = response.getWriter();
// Returns a reference to the ServletContext in which this servlet is running.
ServletContext application = this.getServletContext();
// 从当前application中读取属性accessCount的值
Integer accessCount = (Integer)application.getAttribute("accessCount");
if(accessCount == null) {
accessCount = new Integer(0);
} else {
accessCount = new Integer(accessCount.intValue() + 1);
}
// 向当前application中插入键(key,属性值(value对
application.setAttribute("accessCount", accessCount);
out.println("<html><head><title>ServletContext测试</title></head><br>"
+ "<body><td>" + accessCount +"</td>\n"
+ "</body></html>");
}
}
web.xml
<servlet> <description>This is the description of my J2EE component</description> <display-name>This is the display name of my J2EE component</display-name> <servlet-name>TestServletContext</servlet-name> <servlet-class>TestServletContext</servlet-class> </servlet> <servlet-mapping> <servlet-name>TestServletContext</servlet-name> <url-pattern>/servlet/TestServletContext</url-pattern> </servlet-mapping>
Servlet类本身位于包中的情况
HelloWorldServlet2
http://localhost:8080/TestServlet01/servlet/HelloWorldServlet2
package com.bjsxt.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet类本身位于包中的情况
* classes中要class文件及其各级目录一起放置
* web中如下设置:<servlet-class>com.bjsxt.servlet.HelloWorldServlet2</servlet-class>
* @author jukey
*
*/
public class HelloWorldServlet2 extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=gb2312");
PrintWriter out = response.getWriter();
out.println("Hello World!");
}
}
web.xml
<servlet>
<description>This is the description of my J2EE component</description>
<display-name>This is the display name of my J2EE component</display-name>
<servlet-name>HelloWorldServlet2</servlet-name>
<servlet-class>com.bjsxt.servlet.HelloWorldServlet2</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloWorldServlet2</servlet-name>
<url-pattern>/servlet/HelloWorldServlet2</url-pattern>
</servlet-mapping>
星期日, 十二月 20, 2015 22:28:38