日期:2014-05-17  浏览次数:20839 次

各位高手,怎样在jsp/servlet中删除cookie值?
这是我看到的两段程序代码,分为1.建立cookie和2.删除cookie两端。

1.建立cookie代码建立一个名为color1,值为red的cookie。

2.删除cookie的代码是删除名为color1的cookie。

问题:

在建立cookie后执行删除cookie的代码,cookie并没有被删除,我感觉是因为删除的是定义的temp值而不是cookie数组的名为color1的值,如果temp是color1的一个引用还好(怎么设置为引用或者指针呢?)

请各位高手告诉我怎么在程序中删除cookie值,包括删除指定的cookie值和删除所有cookie值。

不胜感激。

附上两段源代码:

1.建立cookie的代码

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 SetCookie extends HttpServlet {

/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.

* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

response.setContentType("text/html;charset=gbk");
PrintWriter out = response.getWriter();
try {
//当用户访问该servlet时,就将该信息写到该用户的servlet中

//1.现在在服务器端创建第一个cookie

Cookie mycookie = new Cookie("color1","red");

//2.该cookie存在的时间
mycookie.setMaxAge(30);
//如果你不设置存在时间,那么该cookies将不会被保存

//3.将该cookie写回到客户端
response.addCookie(mycookie);

out.println("已经创建了cookie");

} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
out.flush();
out.close();
}

}


2.删除cookie的代码

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 DeleteCookie extends HttpServlet {

/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.

* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

response.setContentType("text/html;charset=gbk");
PrintWriter out = response.getWriter();
try {
//从客户端得到所有的cookies信息
Cookie[] allCookies = request.getCookies();

int i = 0;
//如果allCookies不为空
if(allCookies != null){

//从中取出cookies
for(i = 0;i < allCookies.length;i++){
//依次取出
Cookie temp = allCookies[i];

if(temp.getName().equals("color1")){
//将该cookies删除
temp.setMaxAge(0);
out.println("删除了color1这个cookie")