0

我制作了一个简单的 servlet,将随机数存储为 cookie id,当单击“新身份”时,cookie id 应该改变,但问题是 id 没有改变。下面是我的代码,

import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class Cookies extends HttpServlet 
{
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException 
    {
       response.setContentType("text/html");
       PrintWriter out=response.getWriter();

       Cookie coki[]=request.getCookies();
       Cookie tokenCookie=null;
       if(coki!=null)
       {
           for(int i=0;i<coki.length;i++)
           {

               if(coki[i].getName().equals("token"))
               {
                   tokenCookie=coki[i];
                   break;
               }
           }
       }

       String resetParam=request.getParameter("resetParam");
       if(tokenCookie==null || (resetParam!=null && resetParam.equals("yes")))
       {
           Random rnd=new Random();
           long cookieid=rnd.nextLong();
           out.println("Welcome. A new token "+cookieid+" is now established");
           tokenCookie =new Cookie("token",Long.toString(cookieid));
           tokenCookie.setComment("Cookie named token to identity user");
           tokenCookie.setMaxAge(-1);
           tokenCookie.setPath("/ServletPractice/Cookies");
           response.addCookie(tokenCookie);
       }
       else
       {
           out.println("Welcome back. Your token id is "+tokenCookie.getValue()+"");
       }
       String requestURLSame=request.getRequestURL().toString();
       String requestURLNew=request.getRequestURL()+"?requestParam=yes";

       out.println("Click <a href="+requestURLSame+">here</a> to browse with same identity");
       out.println("Click <a href="+requestURLNew+">here</a> to browse with new identity");
       out.close();
    }  
}

当我在我的 chrome 浏览器中运行上面的 servlet 时,它会显示,如果我单击“新身份”的链接,则显示的 id 不会更改,但字符串会从“欢迎”更改为“欢迎回来”。

请引导我完成。提前致谢。

4

0 回答 0