1. 发送Cookie对象
java.util.Date date=new java.util.Date(); Cookie c=new Cookie("lastVisited",date.toString()); c.setMaxAge(60*60*24);//设置有效时间. c.setPath(); //设置路径 response.addCookie(c);//存储Cookie文件
2.读取Cookie
Cookie[] cookies=request.getCookies(); Cookie c=null; if(cookies!=null){ for(int i=0;i<cookies.length;i++){ c=cookies[i]; out.println("Cookie name:"+c.getName()+"<br>"); out.println("Cookie value:"+c.getValue()+"<br>"); } }
3.修改Cookie
Cookie[] cookies=request.getCookies(); Cookie c=null; for(int i=0;i<cookies.length;i++){ c=cookies[i]; if(c.getName().equal("lastvisited")){ c.setValue("2010-11-11"); c.setMaxValue(60*60*24); response.addCookie(c); } }
4.删除Cookie
Cookie[] cookies=request.getCookies(); Cookie c=null; for(int i=0;i<cookies.length;i++){ c=cookies[i]; if(c.getName().equal("lastvisited")){ c.setMaxValue(0); response.addCookie(c); } }
使用Cookie的注意事项:
1.Cookie的大小和数量是有限制的.只能是英文字符和数字,不能是汉字.
2.Cookie的个人硬盘上所保存的文本信息以明文格式进行保存.没有任何加密措施.
3.浏览器用户可以设定不适用Cookie
例子:
web project:Cookie
编写username.html
编写SetCookieServlet.java(Servlet),映射为/servlet/setServlet
编写GetCookieServlet.java(Servlet)映射为/servlet/getServlet
编写StringUtil.java 用来过滤一些恶意代码.
username.html:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>无标题文档</title> </head> <body> <form id="form1" name="form1" method="post" action="/Cookie/servlet/setCookies"> <table width="361" border="1"> <tr> <th colspan="2" scope="col"><div align="left">请输入用户名:</div></th> </tr> <tr> <th scope="row">用户名:</th> <td><input type="text" name="username" id="username" /></td> </tr> <tr> <th scope="row"><input type="reset" name="reset" id="reset" value="重置" /></th> <td><input type="submit" name="submit" id="submit" value="提交" /></td> </tr> </table> </form> </body> </html>
SetCookieServlet.java:
import java.io.IOException; import java.io.PrintWriter; import java.text.SimpleDateFormat; import java.util.Date; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.v512.guestbook.StringUtil; public class SetCookiesServlet extends HttpServlet { private static final long serialVersionUID = 1L; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String username=request.getParameter("username"); String outputContent=null; if (!StringUtil.validateNull(username)) { Cookie cookie1=new Cookie ("username",StringUtil.filterHtml(username)); cookie1.setMaxAge(24*60*60*30); SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd"); Cookie cookie2=new Cookie("lastVisited", sdf.format(new Date())); cookie2.setMaxAge(24*60*60*30); response.addCookie(cookie1); response.addCookie(cookie2); outputContent="本次登录的用户名与时间已经写到Cookie当中.<br><a href='/Cookie/servlet/getCookies'>读取Cookie</a><br>"; }else { outputContent="本次记录没有写到Cookie当中.<br><a href='/Cookie/username.html'>重新输入</a><br>"; } response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">"); out.println("<HTML>"); out.println(" <HEAD><TITLE>set cookie</TITLE></HEAD>"); out.println(" <BODY>"); out.println("<h2>"+outputContent+"</h2>"); out.println(" </BODY>"); out.println("</HTML>"); out.flush(); out.close(); } }
3.GetCookieServlet.java
import java.io.IOException; import java.io.PrintWriter; import java.net.CookiePolicy; 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 GetCookiesServlet extends HttpServlet { private static final long serialVersionUID = 1L; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">"); out.println("<HTML>"); out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>"); out.println(" <BODY>"); out.println("<h2>从Cookie读取的上次登录日期与用户名</h2>"); Cookie[] cookies=request.getCookies(); Cookie cookie=null; if (cookies!=null) { for (int i = 0; i < cookies.length; i++) { cookie=cookies[i]; if (cookie.getName().equals("username")) { out.println("用户名:"+cookie.getValue()+"<br>"); } if (cookie.getName().equals("lastVisited")) { out.println("上次登录的日期:"+cookie.getValue()+"<br>"); } } } out.println(" </BODY>"); out.println("</HTML>"); out.flush(); out.close(); } }
StringUtil.java
public class StringUtil { public static boolean validateNull(String args) { if (args == null || args.length() == 0) { return true; } else { return false; } } public static String ChangeNull(String source, String target) { if (source == null || source.length() == 0 || source.equalsIgnoreCase("null")) { return target; } else { return source; } } // 过滤一些恶意的代码 public static String filterHtml(String input) { if (input == null) { return null; } if (input.length() == 0) { return input; } input = input.replaceAll("&", "&"); input = input.replaceAll("<", "<"); input = input.replaceAll(">", ">"); input = input.replaceAll(" ", " "); input = input.replaceAll("'", "'"); input = input.replaceAll("\"", """); input = input.replaceAll("\n", "<br>");// 空格过滤一定要放在最后面! return input; } }