一、servlet功能代码:
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String value=request.getParameter("oper");
if("add".equals(value)){
//创建Cookie对象
Cookie cookieName=new Cookie("ckname", "zsf");
Cookie cookiePass=new Cookie("ckpass", "zsf");
cookiePass.setPath("/web06/servlet/");//设置有效路径
//注意:项目名称/路径
//响应
response.addCookie(cookieName);
response.addCookie(cookiePass);
request.getRequestDispatcher("./index.jsp").forward(request, response);
}else if("delete".equals(value)){
//删除Cookie原理
Cookie cookiePass=new Cookie("ckpass", null);
//删除时要与创建的Cookie的有效路径一致
cookiePass.setPath("/web06/servlet/");
cookiePass.setMaxAge(0);//立马删除 -1关闭浏览器后删除
//响应
response.addCookie(cookiePass);
request.getRequestDispatcher("./index.jsp").forward(request, response);
}else if("select".equals(value)){
//获取所有Cookie信息
Cookie[] cookies=request.getCookies();
if(cookies!=null){
for(Cookie ck:cookies){
System.out.println(ck.getName());
System.out.println(ck.getValue());
}
}
request.getRequestDispatcher("./index.jsp").forward(request, response);
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
index.jsp页面代码:
<a href="./ck.do?oper=add">AddCookie</a>
<a href="./ck.do?oper=delete">DeleteCookie</a>
<a href="./ck.do?oper=select">SelectCookie</a>
二、效果
(1)点击AddCookie
在下面地址中仅显示用户名
http://localhost:8080/web06/
输入下面地址才显示密码和用户名
http://localhost:8080/web06/servlet/ck.do
(2)点击SelectCookie效果如下:
控制台输出
(3)点击DeleteCookie