1

我正在使用cookie来避免havind SID(会话ID)。我尝试使用以下方法设置cookie并在我的jsp文件中检索它,如图所示,但它不起作用。它只显示 HelloSESSIONID。

爪哇

public class Users {

 public void setcookie(){
      Cookie user = new Cookie("User","Miro");
      user.setMaxAge(60*60);
 }

jsp

<%@ page language="java"%>
<% Cookie cookies[] = request.getCookies(); 

           for (int i=0; i<cookies.length; i++) 
       {

        out.println("Hello"+cookies[i].getName()+ "> ");
       }
            %>
4

3 回答 3

2
Cookie user = new Cookie("User","Miro");
user.setMaxAge(60*60);

您也必须发送 cookie:

response.addCookie(user);
于 2013-07-18T04:03:42.867 回答
2

这是一个在 Struts 2 中使用 cookie 的示例。

public class MyAction extends ActionSupport implements ServletResponseAware, ServletRequestAware {

      public int division;

      public String execute() {

        // Load from cookie
        for(Cookie c : servletRequest.getCookies()) {
          if (c.getName().equals("cookieDivision"))
            division=Integer.parseInt(c.getValue());
        }

        // Save to cookie
        Cookie div = new Cookie("cookieDivision", String.format("%d",division));
        div.setMaxAge(60*60*24*365); // Make the cookie last a year
        servletResponse.addCookie(div);

        return "success";
      }

      // For access to the raw servlet request / response, eg for cookies
      protected HttpServletResponse servletResponse;
      @Override
      public void setServletResponse(HttpServletResponse servletResponse) {
        this.servletResponse = servletResponse;
      }

      protected HttpServletRequest servletRequest;
      @Override
      public void setServletRequest(HttpServletRequest servletRequest) {
        this.servletRequest = servletRequest;
      }
    }
于 2013-07-18T06:51:40.393 回答
0

您需要为 cookie 定义路径。例如,要使其在应用程序的所有页面中都可以访问,请使用以下内容

 user.setPath("/");
 or
 user.setDomain("example.com");
于 2013-07-18T06:40:39.363 回答