使用cookie保存会话数据
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用cookie保存会话数据相关的知识,希望对你有一定的参考价值。
import java.io.IOException; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class ShoppingCartViewerCookie extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, Cookie[] cookies = req.getCookies(); if (cookies != null) { for (int i = 0; i < cookies.length; i++) { if (cookies[i].getName().equals("sessionid")) { sessionid = cookies[i].getValue(); break; } } } // If the session ID wasn't sent, generate one. // Then be sure to send it to the client with the response. if (sessionid == null) { sessionid = generateSessionId(); Cookie c = new Cookie("sessionid", sessionid); res.addCookie(c); } out.println("<HEAD><TITLE>Current Shopping Cart Items</TITLE></HEAD>"); out.println("<BODY>"); // Cart items are associated with the session ID // Print the current cart items. out.println("You currently have the following items in your cart:<BR>"); if (items == null) { out.println("<B>None</B>"); } else { out.println("<UL>"); for (int i = 0; i < items.length; i++) { out.println("<LI>" + items[i]); } out.println("</UL>"); } // Ask if they want to add more items or check out. out.println("<FORM ACTION="/servlet/ShoppingCart" METHOD=POST>"); out.println("Would you like to<BR>"); out.println("<INPUT TYPE=SUBMIT VALUE=" Add More Items ">"); out.println("<INPUT TYPE=SUBMIT VALUE=" Check Out ">"); out.println("</FORM>"); // Offer a help page. out.println("For help, click <A HREF="/servlet/Help" + "?topic=ShoppingCartViewerCookie">here</A>"); out.println("</BODY></HTML>"); } } } }
以上是关于使用cookie保存会话数据的主要内容,如果未能解决你的问题,请参考以下文章