0

.jsp 文件

<% 

               String stateforcookie=request.getParameter("stateforcookie");
               if(stateforcookie != null ) {
               Cookie cookies2 = new Cookie("statecookie",stateforcookie);

               cookies2.setMaxAge(365 * 24 * 60 * 60);
               response.addCookie(cookies2);
               }                  
               String state=request.getParameter("state");
               Cookie[] cookies2=null;
               cookies2 = request.getCookies();
               out.print(cookies2);

               if (state==null) { if(cookies2 != null)
                                    state=cookies2[0].getValue(); }
              if(cookies2[0].getValue() == null) {
               %>

<body onload="po(0);">
<% }else { %>
<body onload="po(1);">
<% } %>

<div id="popup">
<div id="contenttt">
<form method="post" action="home.jsp">
Choose Your State:<input id="popuptext" type="text" name="stateforcookie" />
 <input id="popupclose" type="submit" value="submit" />   
</form>
</div>      
</div>

javascript:

<script type="text/javascript">  
function po(i) {

 if(i==1){
 $('#popup').hide("slow");
    }
  else if(i==0){$('#popup').show("slow");}
}
$(function(){   
     $('#popupclose').click(function(){

        $('#popup').hide("slow");

    });

});   
</script>

1.这里我正在尝试将值存储到cookie,如果cookie为空,它将弹出一个带有文本框的窗口。如果 cookie 不为空,则不会显示弹出窗口。

但我遇到了线路问题 - out.print(cookies2); 它打印:-

[Ljavax.servlet.http.Cookie;@1d6bff7

  1. if(cookies2[0].getValue() == null) 抛出空指针异常.. 即使删除所有浏览数据后,我也会遇到同样的错误
4

1 回答 1

1

如果不为 cookie 赋值,当它为 null 时您无法进行比较,因此您的弹出窗口将不会被执行。cookies2 第一次为空,它抛出空指针异常

if(cookies2 != null) { if(cookies2[0].getValue() != null) {} }

我修改了你的,试试这个弹出窗口。你应该使用 for 循环来获取存储在 cookie 中的值,就像我在下面所做的那样

<% 

           String stateforcookie=request.getParameter("stateforcookie");
      out.println(stateforcookie);
      Cookie cookies2=null;
      Cookie[] cookies1=null;
           if(stateforcookie != null ) {
           cookies2 = new Cookie("statecookie",stateforcookie);

           cookies2.setMaxAge(365 * 24 * 60 * 60);
           response.addCookie(cookies2);

           }

           String state=request.getParameter("state");

           cookies1 = request.getCookies();

           if(cookies1 != null) 
           for (int i = 0; i < cookies1.length; i++) {
               if (cookies1[i].getName().equals("statecookie")) {
                out.println(cookies1[i].getValue());
                state=cookies1[i].getValue();
                session.setAttribute("statecookie",state);
                 break;
               }
             }

           %>
于 2013-03-23T19:28:46.823 回答