/* Copyright (c) SEMM NL All rights reserved.
Author : Paul Hamaker. Part of JavaLessons.com
This code is for educational purposes only. Use at own risk.*/

1. import javax.servlet.http.*; 

2. import javax.servlet.*; 

3. import java.io.*; 

4.  

5. public class ServCook 

6.     extends HttpServlet 

7.

8.   PrintWriter out ; 

9.  

10.   public void 

11.   doGet ( HttpServletRequest req, HttpServletResponse resp ) 

12.     throws ServletException, IOException 

13.   { 

14.     resp.setContentType ( "text/html" ) ; 

15.  

16.     Cookie[] cks = req.getCookies(); 

17.  

18.     if ( cks != null

19.     { 

20.       startHTML ( resp )  ; 

21.       out.println( "Cookie(s) received from browser by servlet" ); 

22.       out.println ( "<UL>" ) ; 

23.  

24.       Cookie ck ; 

25.       for ( int i=0; i < cks.length ; i++ ) 

26.       { 

27.         ck = cks[i] ; 

28.         out.println ( "<LI>" + "name = "

29.          ck.getName() ) ; 

30.         out.println ( "<LI>" + "value = "

31.          ck.getValue() ) ; 

32.       } 

33.       out.println ( "</UL>" ) ; 

34.     } 

35.     else 

36.     { 

37.       Cookie newc = new Cookie

38.                          "someid"

39.                            "ab@dawk.nl" ); 

40.       newc.setMaxAge( 7*24*60*60 ); 

41.       newc.setPath("/pht4"); 

42.  

43.       resp.addCookie ( newc ) ; 

44.       startHTML ( resp ) ; 

45.       out.println ( "new cookie sent to browser"); 

46.     } 

47.  

48.     out.println ( "</BODY>" ) ; 

49.     out.println ( "</HTML>" ) ; 

50.  

51.     out.flush (); 

52.     out.close (); 

53.     out = null

54.   } 

55.  

56.   private void startHTML ( HttpServletResponse resp ) 

57.       throws IOException, ServletException 

58.   { 

59.     out = resp.getWriter(); 

60.  

61.     out.println ( "<HTML>" ) ; 

62.     out.println ( "<HEAD><TITLE>" ) ; 

63.     out.println ( "Cookies servlet" ) ; 

64.     out.println ( "</TITLE></HEAD>" ) ; 

65.  

66.     out.println ( "<BODY>" ) ; 

67.     out.println ( "<H1>Cookies servlet 1.05</H1>" ) ; 

68.   } 

69. } /* 

70. ========= other source file(s) ================== 

71.       Cookie c = new Cookie( "nm", "val" ); 

72.       c.setDomain ( ".znorro.net" ) ; 

73.       resp.addCookie ( c ) ; 

74. users.znorro.net 

75. abusers.znorro.net 

76. xxx.znorro.net 

77.  

78. === MSIE cookie : === 

79. someid  ab%40dawk.nl  localhost/pht4 .... 

80. =========== 

81. ck.setMaxAge(0); 

82. resp.addCookie(ck); 

83.  */