1、对于Cookie的理解,在我看来其实就是存储客户端的一些个性化信息,简单一点的就是username、password之类的
2、在servlet中编程实现Cookie
code
import java.io.IOException; import java.io.PrintWriter; 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 CookieServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO Auto-generated method stub //super.doGet(req, resp); doPost(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO Auto-generated method stub //super.doPost(req, resp); PrintWriter out=resp.getWriter(); Cookie ck=new Cookie("username","cjc"); //expired time 5 hours ck.setMaxAge(3600*5); resp.addCookie(ck); Cookie[] cookies=req.getCookies(); out.println("<html>"); out.println("<head><title>Cookie</title></head>"); out.println("<body><font size=\"+4\"><b>"); if(cookies==null){ out.println("<hr><br>There is no cookie!"); }else{ out.println("<hr><br>"); for(int i=0;i<cookies.length;i++){ out.println("name:"+cookies[i].getName()); out.println("value:"+cookies[i].getValue()); } } out.println("</b></font></body>"); out.println("</html>"); } }
第一次运行
第二次运行
时间: 2024-10-14 00:44:01