`
onehao
  • 浏览: 13015 次
  • 性别: Icon_minigender_1
  • 来自: 北京
最近访客 更多访客>>
社区版块
存档分类
最新评论

Servlet与JSP核心编程 ---- 8

阅读更多

8.6 使用cookie的属性

 

 

• getPath/setPath

– 读取/设置cookie适用的路径。如果未指定,则cookie

适用于含有当前页面的目录中的URL,以及该目录之

下的URL。

• getSecure/setSecure

– 读取/设置标志,标示cookie是否只应适用于SSL连接

,或者适用于所有连接。

• getValue/setValue

– 读取/设置与cookie关联的值。对于新的cookie,我们

将值提供给构造函数,而非setValue。对于输入cookie

组成的数组,我们使用getName找到感兴趣的cookie,

然后调用所获得对象的getValue方法。如果设置了某

个输入cookie的值,我们依旧需要用

response.addCookie将它发送回去。

 

 

 

8.7 区分会话cookie和持续性cookie

1.该servlet设置6个输出cookie。3个没有明确设置时效(即默认情况下的负值),意指它只适用当前浏览会话---直到重启浏览器为止。另外3个使用segMaxAge规定浏览器应该将它们写到磁盘上,并且应该保持一个小时,而不管用户通过那种方式初始化新的浏览会话--重启浏览器还是重启计算机。

2.该servlet使用request.getCookies查找所有输入cookie,将他们的名称和值显示在一个html表格中。

 

package coreservlets;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
/** Creates a table of the cookies associated with
* the current page. Also sets six cookies: three
* that apply only to the current session
* (regardless of how long that session lasts)
* and three that persist for an hour (regardless
* of whether the browser is restarted).
*/
public class CookieTest extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
for(int i=0; i<3; i++) {
// Default maxAge is -1, indicating cookie
// applies only to current browsing session.
Cookie cookie = new Cookie("Session-Cookie-" + i,
"Cookie-Value-S" + i);
response.addCookie(cookie);
cookie = new Cookie("Persistent-Cookie-" + i,
"Cookie-Value-P" + i);
// Cookie is valid for an hour, regardless of whether
// user quits browser, reboots computer, or whatever.
cookie.setMaxAge(3600);
response.addCookie(cookie);
}
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String docType =
"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " +
"Transitional//EN\">\n";
String title = "Active Cookies";
out.println(docType +
"<HTML>\n" +
"<HEAD><TITLE>" + title + "</TITLE></HEAD>\n" +
"<BODY BGCOLOR=\"#FDF5E6\">\n" +
"<H1 ALIGN=\"CENTER\">" + title + "</H1>\n" +
"<TABLE BORDER=1 ALIGN=\"CENTER\">\n" +
"<TR BGCOLOR=\"#FFAD00\">\n" +
" <TH>Cookie Name\n" +
" <TH>Cookie Value");
Cookie[] cookies = request.getCookies();
if (cookies == null) {
out.println("<TR><TH COLSPAN=2>No cookies");
} else {
Cookie cookie;
for(int i=0; i<cookies.length; i++) {
cookie = cookies[i];
out.println("<TR>\n" +
" <TD>" + cookie.getName() + "\n" +
" <TD>" + cookie.getValue());
}
}
out.println("</TABLE></BODY></HTML>");
}
}
 

 

8.8 基本的cookie实用程序。

1.查找名称的cookie

 

package coreservlets;
import javax.servlet.*;
import javax.servlet.http.*;
/** Two static methods for use in cookie handling. */
public class CookieUtilities {
/** Given the request object, a name, and a default value,
* this method tries to find the value of the cookie with
* the given name. If no cookie matches the name,
* the default value is returned.
*/
public static String getCookieValue
(HttpServletRequest request,
String cookieName,
String defaultValue) {
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for(int i=0; i<cookies.length; i++) {
Cookie cookie = cookies[i];
if (cookieName.equals(cookie.getName())) {
return(cookie.getValue());
}
}
}
return(defaultValue);
}
/** Given the request object and a name, this method tries
* to find and return the cookie that has the given name.
* If no cookie matches the name, null is returned.
*/
public static Cookie getCookie(HttpServletRequest request,
String cookieName) {
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for(int i=0; i<cookies.length; i++) {
Cookie cookie = cookies[i];
if (cookieName.equals(cookie.getName())) {
return(cookie);
}
}
}
return(null);
}
}

 

 

2.创建长生存期的cookie

 

package coreservlets;
import javax.servlet.http.*;
/** Cookie that persists 1 year. Default Cookie doesn't
* persist past current browsing session.
*/
public class LongLivedCookie extends Cookie {
public static final int SECONDS_PER_YEAR = 60*60*24*365;
public LongLivedCookie(String name, String value) {
super(name, value);
setMaxAge(SECONDS_PER_YEAR);
}
}

 

8.9 使用cookie使用程序

 

package coreservlets;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
/** A variation of the RepeatVisitor servlet that uses
* CookieUtilities.getCookieValue and LongLivedCookie
* to simplify the code.
*/
public class RepeatVisitor2 extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
boolean newbie = true;
String value =
CookieUtilities.getCookieValue(request, "repeatVisitor2",
"no");
if (value.equals("yes")) {
newbie = false;
}
String title;
if (newbie) {
LongLivedCookie returnVisitorCookie =
new LongLivedCookie("repeatVisitor2", "yes");
response.addCookie(returnVisitorCookie);
title = "Welcome Aboard";
} else {
title = "Welcome Back";
}
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String docType =
"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " +
"Transitional//EN\">\n";
out.println(docType +
"<HTML>\n" +
"<HEAD><TITLE>" + title + "</TITLE></HEAD>\n" +
"<BODY BGCOLOR=\"#FDF5E6\">\n" +
"<H1 ALIGN=\"CENTER\">" + title + "</H1>\n" +
"</BODY></HTML>");
}
}

 

 

8.10 修改cookie的值:记录用户的访问计数

要替换cookie之前的值,需要发送相同的cookie名称,但要使用不同的cookie值。如果您想使用输入cookie对象,那么不要忘记调用response.addCooke;只是调用setValue是没有效果的。还需要调用setMaxAge,setPath等,重新应用所有的相关cookie属性。

 

要指示浏览器删除一个cookie,只要使用setMaxAge将它的最大时效设为0。

 

 

package coreservlets;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
/** Servlet that prints per-client access counts. */
public class ClientAccessCounts extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String countString =
CookieUtilities.getCookieValue(request,
"accessCount",
"1");
int count = 1;
try {
count = Integer.parseInt(countString);
} catch(NumberFormatException nfe) { }
LongLivedCookie c =
new LongLivedCookie("accessCount",
String.valueOf(count+1));
response.addCookie(c);
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Access Count Servlet";
String docType =
"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " +
"Transitional//EN\">\n";
out.println(docType +
"<HTML>\n" +
"<HEAD><TITLE>" + title + "</TITLE></HEAD>\n" +
"<BODY BGCOLOR=\"#FDF5E6\">\n" +
"<CENTER>\n" +
"<H1>" + title + "</H1>\n" +
"<H2>This is visit number " +
count + " by this browser.</H2>\n" +
"</CENTER></BODY></HTML>");
}
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics