首页 > 代码库 > 对Cookie进行增删改查
对Cookie进行增删改查
public class CookieServletDemo extends HttpServlet {
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>");
//cookie添加 ---向客户端添加/修改cookie
//addCookie(request,response);
readCookie(request,response);
//delCookie(request,response);
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
}
//读取客户端发来的cookie ---不同浏览器,cookie是不共享的
private void readCookie(HttpServletRequest request,
HttpServletResponse response) throws IOException {
Cookie cs[] = request.getCookies();
if(cs!=null){
for(Cookie c:cs){
String key = c.getName();
String value = http://www.mamicode.com/c.getValue();
value = http://www.mamicode.com/URLDecoder.decode(value,"utf-8");
int maxAge = c.getMaxAge();//cookie机制安全性考虑,不让读取,因此返回都是-1
System.out.println(key+","+value+","+maxAge);
}
}
}
//添加/修改
private void addCookie(HttpServletRequest request,
HttpServletResponse response) throws IOException {
//String name="hncu";
String name = "湖南城院";
name = URLEncoder.encode(name, "utf-8");//如果是中文,则需要编码
Random r = new Random();
name = name+r.nextInt(1000);
System.out.println(name);
Cookie coo = new Cookie("school", name);
coo.setMaxAge(60*60);//为该cookie设置有效期(浏览器会自动把它转变成过期时间)
coo.setPath(request.getContextPath());//由路径控制访问权限
response.addCookie(coo);//如果存在相同key的cookie则是覆盖(修改),若不存在则是新建(添加)
}
//删除cookie ==其实就是向浏览器添加一个maxAge为0的cookie, 该cookie的key为将要被删除cookie的,要注意权限(cookie路径要设得和创建时完全一样)
private void delCookie(HttpServletRequest request,
HttpServletResponse response) throws IOException {
//删除key为"school"的cookie
Cookie coo = new Cookie("school", "aa");
coo.setMaxAge(0);//效期设为0即是代表删除
coo.setPath(request.getContextPath());//权限控制:删除时,路径必须和创建时设置的完全一样,否则无权删除
response.addCookie(coo);//删除
}
}
---------------------------------------------------------------------------------------------------------------------------------------------
<a href="http://www.mamicode.com/CookieServletDemo">CookieDemo基本用法演示</a>
<h3>以下servlet用于演示cookie的访问权限</h3>
<form action="servlet/CookieServletDemo2" method="post">
Name:<input type="text" name="name"/> <br/>
<input type="submit" value="http://www.mamicode.com/提交"/>
</form>
对Cookie进行增删改查