Javax。servlet。http。Java中的Cookie类

许多网站使用称为cookie的小文本字符串来存储连接之间的持久客户端状态。Cookie从服务器传递到客户端,然后在请求和响应的HTTP头中再次传递。服务器可以使用cookie来指示会话ID、购物车内容、登录凭据、用户首选项等。

null

饼干是怎么工作的?

How cookies work?

从上图可以看出,当用户第一次请求页面时,服务器和资源一起发送一个cookie对象以存储在客户机上。此对象可能包含请求的详细信息。稍后,如果用户再次请求相同的资源,它会随请求一起发送存储的cookie,服务器可以使用cookie来进一步增强用户的体验。

Cookie的属性:

  • 名称=值对: 这描述了存储在cookie中的实际信息。名称和值均不应包含空格或以下任何字符: [ ] ( ) = , ” / ? @ : ; 有效的cookie名称-值对示例:
     Set-Cookie:session-id = 187-4969589-3049309
  • 域名: 默认情况下,cookie应用于它来自的服务器。如果cookie最初由www.foo设置。实例com,浏览器只会将cookie发送回www.foo。实例通用域名格式。然而,站点也可以指示cookie应用于整个子域,而不仅仅是原始服务器。例如,该请求为整个foo设置一个用户cookie。实例com域: 浏览器将把这个cookie回显到www.foo。实例com,还有洛萨。福。实例伊丽莎。福。实例以诺。福。实例com和foo中的任何其他主机。实例com域。但是,服务器只能为其直接所属的域设置cookie。www.foo。实例com无法为www.geeksforgeks设置cookie。例如,org。com,或。com,无论它如何设置域。
     Set-Cookie: user = geek ;Domain =.foo.example.com
  • 路径: 当从同一台服务器请求子树中的文档时,客户端会回显该cookie。但是,它不会在网站的其他目录中使用cookie。
    Set-Cookie: user = geek; Path =/ restricted
  • 到期: 该日期过后,浏览器应该从缓存中删除cookie。
     Set-Cookie: user = geek; expires = Wed, 21-Feb-2017 15:23:00 IST
  • 最大年龄: 此属性将cookie设置为在经过特定秒数后过期,而不是在特定时刻过期。例如,此cookie在第一次设置后一小时(3600秒)过期。
    Set-Cookie: user = "geek"; Max-Age = 3600

建造师 :创建具有指定名称-值对的cookie。

Syntax : public Cookie(String name, String value)
Parameters :
name : name of the cookie
value : value associated with this cookie

方法:

  1. setDomain(): 设置此cookie可见的域。域在前面的cookie部分的属性中有详细说明。
    Syntax : public void setDomain(String pattern)
    Parameters :
    pattern : string representing the domain in which this cookie is visible.
  2. getDomain(): 返回此cookie可见的域。
    Syntax : public String getDomain()
  3. setComment(): 指定此cookie的用途。
    Syntax : public void setComment(String purpose)
    Parameters :
    purpose : string representing the purpose of this cookie.
  4. getComment() :返回表示此cookie用途的字符串。
    Syntax : public String getComment()
  5. setMaxAge(): 指定此cookie过期之前经过的时间(秒)。
    Syntax : public void setMaxAge(long time)
    Parameters :
    time : time in seconds before this cookie expires
  6. getMaxAge(): 返回此cookie的最大年龄组件。
    Syntax : public String getMaxAge()
  7. setPath(): 指定客户端应将cookie返回到的cookie路径。
    Syntax : public void setPath(String path)
    Parameters :
    path : path where this cookie is returned
  8. getPath(): 返回此cookie的路径组件。
    Syntax : public String getMaxAge()
  9. setSecure(): 指示发送此cookie时是否使用安全协议。默认值为false。
    Syntax : public void setSecure(boolean secure)
    Parameters:
    secure - If true, the cookie can only be sent over a secure
    protocol like https. 
    If false, it can be sent over any protocol.
  10. getSecure(): 如果必须删除此cookie,则返回true 通过安全协议发送,否则为假。
    Syntax : public boolean getSecure()
  11. getName(): 返回cookie的名称。
     Syntax : public String getName()
  12. setValue(): 初始化后为cookie分配新值。
    Syntax : public void setValue(String newValue)
    Parameters :
    newValue - a String specifying the new value
  13. getValue: 返回cookie的值。
    Syntax : public String getValue()
  14. getVersion(): 如果cookie符合最初的Netscape规范,则返回0;1如果cookie符合RFC 2965/2109
    Syntax : public int getVersion()
  15. setVersion(): 用于设置此cookie使用的cookie协议的版本。
    Syntax :public void setVersion(int v)
    Parameters :
    v - 0 for original Netscape specification; 1 for RFC 2965/2109
    
  16. 克隆(): 返回此cookie的副本。
    Syntax : public Cookie clone()

下面是一个简单servlet程序的Java实现,当用户第一次请求cookie时,该程序会在浏览器中存储cookie,然后在进一步请求时,它会显示存储的cookie。

// Java program to illustrate methods
// of Cookie class
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class cookieTest
*/
@WebServlet ( "/cookieTest" )
public class cookieTest extends HttpServlet
{
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public cookieTest() {
super ();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
*      response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType( "text/html" );
// Create a new cookie with the name test cookie
// and value 123
Cookie cookie = new Cookie( "test_cookie" , "123" );
// setComment() method
cookie.setComment( "Just for testing" );
// setDomain() method
// cookie.setDomain("domain");
// setMaxAge() method
cookie.setMaxAge( 3600 );
// setPath() method
cookie.setPath( "/articles" );
// setSecure() method
cookie.setSecure( false );
// setValue() method
cookie.setValue( "321" );
// setVersion() method
cookie.setVersion( 0 );
response.addCookie(cookie);
PrintWriter pw = response.getWriter();
pw.print( "<html><head></head><body>" );
Cookie ck[] = request.getCookies();
if (ck == null ) {
pw.print( "<p>This is first time the page is requested.</p>" );
pw.print( "<p>And therefore no cookies found</p></body></html>" );
} else {
pw.print( "<p>Welcome Again...Cookies found</p>" );
for ( int i = 0 ; i < ck.length; i++) {
// getName() method
pw.print( "<p>Name :" + ck[i].getName() + "</p>" );
// getValue() method
pw.print( "<p>Value :" + ck[i].getValue() + "</p>" );
// getDomain() method
pw.print( "<p>Domain :" + ck[i].getDomain() + "</p>" );
// getPath() method
pw.print( "<p>Name :" + ck[i].getPath() + "</p>" );
// getMaxAge() method
pw.print( "<p>Max Age :" + ck[i].getMaxAge() + "</p>" );
// getComment() method
pw.print( "<p>Comment :" + ck[i].getComment() + "</p>" );
// getSecure() method
pw.print( "<p>Name :" + ck[i].getSecure() + "</p>" );
// getVersion() method
pw.print( "<p>Version :" + ck[i].getVersion() + "</p>" );
}
pw.print( "<body></html>" );
}
pw.close();
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
*      response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
doGet(request, response);
}
}


输出: 以下输出来自web浏览器- 对于第一个请求:

This is first time the page is requested.
And therefore no cookies found.

对于第二个请求:

Welcome Again...Cookies found
Name :test_cookie
Value :321
Domain :null
Name :null
Max Age :-1
Comment :null
Name :false
Version :0

如何运行上述程序?

首先,确保安装了ApacheTomcat之类的服务器,并使用Eclipse之类的工具进行了配置。只需在服务器或本地浏览器上运行上述程序,输入您正在使用的服务器目录的完整地址即可。 CookieTest servlet,一个执行三项任务的servlet:

  1. 首先,servlet设置一个名为test_cookie的cookie。程序中的其他行设置cookie的属性,如最大年龄、域、值等。
  2. 其次,servlet使用请求。getCookies以查找所有传入的Cookie,并显示它们的名称和其他相应属性。
  3. 如果没有像第一次请求那样找到cookie,则会显示一条简单的显示消息,告诉您这是第一次访问页面。

参考: 官方Java文档

本文由 沙克沙姆·加格和里沙布·马尔西 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 贡献极客。组织 或者把你的文章寄到contribute@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。

© 版权声明
THE END
喜欢就支持一下吧
点赞6 分享