Cookie生成一些随机值

时间:2013-03-16 18:40:25

标签: javascript jsp cookies

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为null,它将弹出一个带有文本框的窗口。如果cookie不为null,则弹出窗口将不会显示。

但是我遇到了line-out.print(cookies2)的问题;它打印: -

  

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

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

1 个答案:

答案 0 :(得分:1)

如果没有为cookie赋值,那么当它为null时如何无法进行比较,这样就不会执行弹出窗口。第一次,cookies2将为null,它会抛出空指针异常

  

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

我修改了你,用这个尝试popUp。你应该使用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;
               }
             }

           %>