Java Tutorial/JSP/Cookie — различия между версиями

Материал из Java эксперт
Перейти к: навигация, поиск
 
м (1 версия)
 
(нет различий)

Текущая версия на 05:07, 1 июня 2010

Create Cookie

<HTML>
    <HEAD>
        <TITLE>Reading a Cookie</TITLE>
    </HEAD>  
    <BODY>
        <H1>Reading a Cookie</H1>  
  
        <%
        Cookie cookie1 = new Cookie("message", "Hello!");
        cookie1.setMaxAge(24 * 60 * 60);
        response.addCookie(cookie1); 
        %> 
        <P>refresh to see the Cookie</p> 
        <%
        Cookie[] cookies = request.getCookies();
    
        for(int i = 0; i < cookies.length; i++) { 
            if (cookies[i].getName().equals("message")) {
                out.println("The cookie says " + cookies[i].getValue());
            }
        }  
        %>
    </BODY>  
</HTML>





Refresh to see the Cookie

<HTML>
    <HEAD>
        <TITLE>Reading a Cookie</TITLE>
    </HEAD>  
    <BODY>
        <H1>Reading a Cookie</H1>  
  
        <%
        Cookie cookie1 = new Cookie("message", "Hello!");
        cookie1.setMaxAge(24 * 60 * 60);
        response.addCookie(cookie1); 
        %> 
        <P>refresh to see the Cookie</p> 
        <%
        Cookie[] cookies = request.getCookies();
    
        for(int i = 0; i < cookies.length; i++) { 
            if (cookies[i].getName().equals("message")) {
                out.println("The cookie says " + cookies[i].getValue());
            }
        }  
        %>
    </BODY>  
</HTML>





Setting and Reading Cookies

<HTML>
    <HEAD>
        <TITLE>Setting and Reading Cookies</TITLE>
    </HEAD>
 
    <BODY
        <%
        Cookie c = new Cookie("message", "Hello!");
        c.setMaxAge(24 * 60 * 60);
        response.addCookie(c); 
        %> 
            
        <%
        Cookie[] cookies = request.getCookies();
        boolean foundCookie = false;
        for(int i = 0; i < cookies.length; i++) { 
            Cookie cookie1 = cookies[i];
            if (cookie1.getName().equals("color")) {
                out.println("bgcolor = " + cookie1.getValue());
                foundCookie = true;
            }
        }  
        if (!foundCookie) {
            Cookie cookie1 = new Cookie("color", "cyan");
            cookie1.setMaxAge(24*60*60);
            response.addCookie(cookie1); 
        }
        %> 
        >
        <H1>Setting and Reading Cookies</H1>
        This page will set its background color using a cookie after refreshing.
    </BODY>
</HTML>