logo

Javax.servlet.http.Cookie class ב-Java

אתרי אינטרנט רבים משתמשים במחרוזות טקסט קטנות הידועות כקובצי Cookie כדי לאחסן מצב מתמשך בצד הלקוח בין חיבורים. קובצי Cookie מועברים משרת ללקוח וחוזר חלילה בכותרות ה-HTTP של בקשות ותגובות. שרת יכול להשתמש בקובצי Cookie כדי לציין מזהי הפעלה תוכן עגלת קניות אישורי כניסה העדפות משתמש ועוד.

איך עוגיות עובדות?

המרה ממחרוזת למספר שלם של java
איך עוגיות עובדות?' title= כפי שניתן לראות מהדיאגרמה לעיל, כאשר משתמש מבקש לראשונה עבור דף, השרת יחד עם המשאב שולחים אובייקט קובץ Cookie לאחסון במחשב של הלקוח. אובייקט זה עשוי להכיל פרטים על הבקשה. כעת מאוחר יותר אם המשתמש יבקש שוב את אותו משאב הוא שולח יחד עם הבקשה את קובץ ה-cookie מאוחסן אשר יכול לשמש את השרתים כדי לשפר עוד יותר את חוויית המשתמש. תכונות של Cookie:
    שם = זוג ערכים:זה מתאר את המידע בפועל המאוחסן בתוך ה-cookie. השם או הערך לא צריכים להכיל רווח לבן או כל אחד מהתווים הבאים: [ ] ( ) = ' / ? @ : ; דוגמה לצמד שם-ערך חוקי של קובצי Cookie:
     Set-Cookie:session-id = 187-4969589-3049309
    תְחוּם: By default a cookie applies to the server it came from. If a cookie is originally set by www.foo.example.com the browser will only send the cookie back to www.foo.example.com. However a site can also indicate that a cookie applies within an entire subdomain not just at the original server. For example this request sets a user cookie for the entire foo.example.com domain: The browser will echo this cookie back not just to www.foo.example.com but also to lothar.foo.example.com eliza.foo.example.com enoch.foo.example.com and any other host somewhere in the foo.example.com domain. However a server can only set cookies for domains it immediately belongs to. www.foo.example.com cannot set a cookie for www.geeksforgeeks.org example.com or .com no matter how it sets the domain.
     Set-Cookie: user = geek ;Domain =.foo.example.com
    נָתִיב: When requesting a document in the subtree from the same server the client echoes that cookie back. However it does not use the cookie in other directories on the site.
    Set-Cookie: user = geek; Path =/ restricted
    פג תוקף: The browser should remove the cookie from its cache after that date has passed.
     Set-Cookie: user = geek; expires = Wed 21-Feb-2017 15:23:00 IST
    גיל מקסימלי: This attribute sets the cookie to expire after a certain number of seconds have passed instead of at a specific moment. For instance this cookie expires one hour (3600 seconds) after it’s first set.
    Set-Cookie: user = 'geek'; Max-Age = 3600
בַּנַאִי : Creates a cookie with specified name-value pair.
  Syntax :   public Cookie(String name String value)   Parameters :   name : name of the cookie value : value associated with this cookie 
שיטות:
    setDomain() : Sets the domain in which this cookie is visible. Domains are explained in detail in the attributes of cookie part previously.
      Syntax :   public void setDomain(String pattern)   Parameters :   pattern : string representing the domain in which this cookie is visible.
    getDomain() : Returns the domain in which this cookie is visible.
      Syntax :   public String getDomain()
    setComment() : Specifies the purpose of this cookie.
      Syntax :   public void setComment(String purpose)   Parameters :   purpose : string representing the purpose of this cookie.
    getComment() : Returns the string representing purpose of this cookie.
      Syntax :   public String getComment()
    setMaxAge() : Specifies the time (in seconds) elapsed before this cookie expires.
      Syntax :   public void setMaxAge(long time)   Parameters :   time : time in seconds before this cookie expires
    getMaxAge() : Returns the max age component of this cookie.
      Syntax :   public String getMaxAge()
    setPath(): Specifies a path for the cookie to which the client should return the cookie.
      Syntax :   public void setPath(String path)   Parameters :   path : path where this cookie is returned
    getPath() : Returns the path component of this cookie.
      Syntax :   public String getMaxAge()
    setSecure() : Indicated if secure protocol to be used while sending this cookie. Default value is 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.
    getSecure() : Returns true if this cookie must be sent by a secure protocol otherwise false.
      Syntax :   public boolean getSecure()
    getName() : Returns the name of the cookie.
       Syntax :   public String getName()
    setValue() : Assigns new value to cookie after initialisation.
      Syntax :   public void setValue(String newValue)   Parameters :   newValue - a String specifying the new value
    getValue: Returns the value of the cookie.
      Syntax :   public String getValue()
    getVersion() : Returns 0 if the cookie complies with the original Netscape specification; 1 if the cookie complies with RFC 2965/2109
      Syntax :   public int getVersion()
    setVersion() : Used to set the version of the cookie protocol this cookie uses.
      Syntax :  public void setVersion(int v)   Parameters :   v - 0 for original Netscape specification; 1 for RFC 2965/2109 
    clone() : returns a copy of this cookie.
      Syntax :   public Cookie clone()
Below is a Java implementation of a simple servlet program which stores a cookie in the browser when user first requests for it and then for further requests it displays the cookies stored. Java
// 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('  ');  Cookie ck[] = request.getCookies();  if (ck == null) {  pw.print('

This is first time the page is requested.

'
); pw.print('

And therefore no cookies found



'
); } else { pw.print('

Welcome Again...Cookies found

'
); for (int i = 0; i < ck.length; i++) { // getName() method pw.print('

Name :' + ck[i].getName() + '

'
); // getValue() method pw.print('

Value :' + ck[i].getValue() + '

'
); // getDomain() method pw.print('

Domain :' + ck[i].getDomain() + '

string int
'
); // getPath() method pw.print('

Name :' + ck[i].getPath() + '

'
); // getMaxAge() method pw.print('

Max Age :' + ck[i].getMaxAge() + '

'
); // getComment() method pw.print('

Comment :' + ck[i].getComment() + '

רום
'
); // getSecure() method pw.print('

Name :' + ck[i].getSecure() + '

'
); // getVersion() method pw.print('

Version :' + ck[i].getVersion() + '

'
); } pw.print(' '); } pw.close(); } /** * @see HttpServlet#doPost(HttpServletRequest request HttpServletResponse * response) */ protected void doPost(HttpServletRequest request HttpServletResponse response) throws ServletException IOException { doGet(request response); } }
תְפוּקָה: הפלט הבא הוא מדפדפן אינטרנט- לבקשה הראשונה:
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

כיצד להפעיל את התוכנית לעיל?

ראשית ודא שמותקן שרת כמו Apache Tomcat והוא מוגדר עם הכלי שבו אתה משתמש כמו Eclipse. פשוט הפעל את התוכנית לעיל בשרת או בדפדפן המקומי שלך על ידי הוספת הכתובת המלאה של ספריית השרת שבה אתה משתמש. ה-CookieTest servlet servlet שמבצע שלוש משימות:
  1. ראשית ה-servlet מגדיר קובץ Cookie בשם test_cookie. שורות אחרות בתוכנית קובעות את התכונות של קובץ ה-cookie כמו ערך דומיין גיל מקסימלי וכו'.
  2. שנית, ה-servlet משתמש ב-request.getCookies כדי למצוא את כל העוגיות הנכנסות ולהציג את שמותיהם ותכונות מתאימות אחרות.
  3. אם לא נמצאו עוגיות כפי שקורה בבקשה הראשונה, מוצגת הודעת תצוגה פשוטה שמספרת שזהו הביקור הראשון בדף.
הַפנָיָה: תיעוד ג'אווה רשמי צור חידון