Servlet Cookie Setter : Cookie « Servlet « Java Tutorial

Java Tutorial
1. Language
2. Data Type
3. Operators
4. Statement Control
5. Class Definition
6. Development
7. Reflection
8. Regular Expressions
9. Collections
10. Thread
11. File
12. Generics
13. I18N
14. Swing
15. Swing Event
16. 2D Graphics
17. SWT
18. SWT 2D Graphics
19. Network
20. Database
21. JSP
22. JSTL
23. Servlet
24. Web Services SOA
25. Email
26. J2ME
27. J2EE Application
28. XML
29. Design Pattern
30. Log
31. Security
32. Apache Common
Java
Java Source Code / Java Documentation
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
C# / C Sharp
C# / CSharp Tutorial
ASP.Net
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
PHP
Python
SQL Server / T-SQL
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java Tutorial » Servlet » Cookie 
23. 4. 3. Servlet Cookie Setter
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;

public class MyServlet extends HttpServlet {
   
    public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, java.io.IOException {
    
    Cookie cookie = null;
    //Get an array of Cookies associated with this domain
    Cookie[] cookies = request.getCookies();
    boolean newCookie = false;
    
    //Get the 'mycookie' Cookie if it exists
    if (cookies != null){
        for (int i = 0; i < cookies.length; i++){
            if (cookies[i].getName().equals("mycookie")){
              cookie = cookies[i];
             
        }//end for
    }//end if
       
    if (cookie == null){
       newCookie=true;
      //Get the cookie's Max-Age from a context-param element
      //If the 'cookie-age' param is not set properly
      //then set the cookie to a default of -1, 'never expires'
      int maxAge;
      try{
           maxAge = new Integer(getServletContext().getInitParameter("cookie-age")).intValue();
           catch (Exception e) {
            maxAge = -1;
           }
      
       //Create the Cookie object
     
        cookie = new Cookie("mycookie",""+getNextCookieValue());
        cookie.setPath(request.getContextPath());
        cookie.setMaxAge(maxAge);
        response.addCookie(cookie);
        
        }//end if
        // get some info about the cookie
        response.setContentType("text/html");
        java.io.PrintWriter out = response.getWriter();
    
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Cookie info</title>");  
        out.println("</head>");
        out.println("<body>");
        
        out.println("<h2> Information about the cookie named \"mycookie\"</h2>");
        
        out.println("Cookie value: "+cookie.getValue()+"<br>");
        if (newCookie){
        out.println("Cookie Max-Age: "+cookie.getMaxAge()+"<br>");
        out.println("Cookie Path: "+cookie.getPath()+"<br>");
        }
        
        out.println("</body>");
        out.println("</html>");
    
        out.close();
    
    private long getNextCookieValue(){
    
    /*This produces a cookie value to show how to create Cookie objects. If 
      this method was heavily used in a production environment it may
      produce too many objects; synchronization of a single Date object
      might be better, based on performance testing. At any rate a
      production environment would produce a unique cookie value in a
      different manner such as from a unique database ID. */

    //returns the number of milleseconds since Jan 1, 1970
    return new java.util.Date().getTime();
    
    }


    public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, java.io.IOException {
        
        doGet(request,response);
    
}
<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app
    PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
    "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">

<web-app>
    <servlet><servlet-name>MyServletName</servlet-name>
             <servlet-class>MyServlet</servlet-class>
        <init-param>
            <param-name>
                go
            </param-name>
            <param-value>
                weather
            </param-value>
        </init-param>
             
    </servlet>
    
    <servlet-mapping><servlet-name>MyServletName</servlet-name>
        <url-pattern>/index.html</url-pattern>
    </servlet-mapping>
</web-app>
  Download:  ServletCookieSetter.zip( 90 k)
23. 4. Cookie
23. 4. 1. Add Cookie Servlet
23. 4. 2. Get Cookies Servlet
23. 4. 3. Servlet Cookie Setter
23. 4. 4. Servlet Cookie Reader
23. 4. 5. Get/Set Cookie
23. 4. 6. List Servlet Cookie Information
ww__w_.j__a__v_a___2s.__c__o___m_ | Contact Us
Copyright 2003 - 08 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.