// Fig. 19.9: CookieExample.java // Using cookies. import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class CookieExample extends HttpServlet { private String names[] = { "C", "C++", "Java", "Visual Basic 6" }; private String isbn[] = { "0-13-226119-7", "0-13-528910-6", "0-13-012507-5", "0-13-528910-6" }; public void doPost( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException { PrintWriter output; String language = request.getParameter( "lang" ); Cookie c = new Cookie( language, getISBN( language ) ); c.setMaxAge( 120 ); // seconds until cookie removed response.addCookie( c ); // must precede getWriter response.setContentType( "text/html" ); output = response.getWriter(); // send HTML page to client output.println( "" ); output.println( "Cookies" ); output.println( "" ); output.println( "

Welcome to Cookies!
" ); output.println( "

" ); output.println( language ); output.println( " is a great language." ); output.println( "" ); output.close(); // close stream } public void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException { PrintWriter output; Cookie cookies[]; cookies = request.getCookies(); // get client's cookies response.setContentType( "text/html" ); output = response.getWriter(); output.println( "" ); output.println( "Cookies II" ); output.println( "" ); if ( cookies != null ) { output.println( "

Recommendations

" ); // get the name of each cookie for ( int i = 0; i < cookies.length; i++ ) output.println( cookies[ i ].getName() + " How to Program. " + "ISBN#: " + cookies[ i ].getValue() + "
" ); } else { output.println( "

No Recommendations

" ); output.println( "You did not select a language or" ); output.println( "the cookies have expired." ); } output.println( "" ); output.close(); // close stream } private String getISBN( String lang ) { for ( int i = 0; i < names.length; ++i ) if ( lang.equals( names[ i ] ) ) return isbn[ i ]; return ""; // no matching string found } } /************************************************************************** * (C) Copyright 1999 by Deitel & Associates, Inc. and Prentice Hall. * * All Rights Reserved. * * * * DISCLAIMER: The authors and publisher of this book have used their * * best efforts in preparing the book. These efforts include the * * development, research, and testing of the theories and programs * * to determine their effectiveness. The authors and publisher make * * no warranty of any kind, expressed or implied, with regard to these * * programs or to the documentation contained in these books. The authors * * and publisher shall not be liable in any event for incidental or * * consequential damages in connection with, or arising out of, the * * furnishing, performance, or use of these programs. * *************************************************************************/