【问题标题】:Passing values using cookies使用 cookie 传递值
【发布时间】:2014-05-14 17:53:58
【问题描述】:

在我的servlet.java 中,我声明了一个 cookie,

String loc = "Some random data";
Cookie thecookie = new Cookie("thecookie", loc);
response.addCookie(thecookie);

稍后在执行一些文件上传后,我再次为此 cookie 设置一个值,

fileTxt = FileUtils.readFileToString(uploadedFile);
thecookie.setValue(fileTxt);

RequestDispatcher rd = request.getRequestDispatcher("thejsppage.jsp");
rd.forward(request, response);

现在在我上面重定向的 jsp 页面中,

<%
  Cookie[] my = request.getCookies();
  for(int i=0;i<my.length;i++){
  String filetext = my[i].getValue().toString();
 }
%>

<div id="editor"><%=filetext %></div>

但是这是返回一个垃圾值,我的错误是什么?

如何使用 cookie 传递值?

我不想使用request.setAttribute("name", value); 方法。

【问题讨论】:

  • 什么垃圾?与文件内容无关?文件有多大?您不能为 cookie 设置太多数据。
  • 该文件仅包含几行..最多 4-5 行,我得到类似 6695A3FB6519959B0959CD6F25B886B5
  • 如果您不打算在 Javascript 客户端访问 cookie,为什么要使用 cookie 而不是会话?
  • 你为什么要在 cookie 中存储文件?
  • 通过使用会话,我遇到了同一浏览器的多选项卡操作问题,会话保持不变。

标签: java jsp cookies


【解决方案1】:

根据我上面的问题,

我变了

<%
  Cookie[] my = request.getCookies();
  for(int i=0;i<my.length;i++){
  String filetext = my[i].getValue().toString();
 }
%>

<div id="editor"><%=filetext %></div>

<%
  Cookie[] my = request.getCookies();
  for(int i=0;i<my.length;i++){
  if(my.getName()=="thecookie"){
  String filetext = my[i].getValue().toString();
   }
  }
%>

<div id="editor"><%=filetext %></div>

现在我可以得到想要的值了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-09-25
    • 2023-03-29
    • 1970-01-01
    • 2013-01-11
    • 2013-11-15
    • 2019-05-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多