日期:2014-05-19  浏览次数:20684 次

jsp 关于cookie记录登陆次数的问题
报错
exception 

org.apache.jasper.JasperException
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:372)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:292)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:236)
javax.servlet.http.HttpServlet.service(HttpServlet.java:802)


root cause 

java.lang.NullPointerException
org.apache.jsp.error_jsp._jspService(error_jsp.java:100)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:94)
javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:324)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:292)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:236)
javax.servlet.http.HttpServlet.service(HttpServlet.java:802)

代码如下
考虑到篇幅 直接上body部分的代码了
check.jsp
<body>
  <%
//解决request请求中的中文乱码
request.setCharacterEncoding("UTF-8");
String username = "";
int visitTimes = 0;
Cookie[] cookies = request.getCookies();
//便利cookie找出登陆账号以及该账号登陆的次数
for(int i = 0 ;cookies != null && i < cookies.length ;i++){
//第一个cookie消息
Cookie cookie = cookies[i];
if(cookie.getName().equals("username")){
username = cookie.getValue();
}
else if(cookie.getName().equals("visitTimes")){
visitTimes = Integer.parseInt(cookie.getValue());
}

}
if(username == null || username.trim().equals("")){
throw new Exception ("您还没有登陆。请先登陆");
}
Cookie visitTimesCookie = new Cookie("visitTimes",Integer.toString(++visitTimes));
response.addCookie(visitTimesCookie);
  %>
  <FORM action="" method="post">
  <TABLE>
  <TR>
  <TD>当前登陆的账号:</TD>
  <TD><%=username%></TD>
  </TR>
  <TR>
  <TD>当前登陆的次数:</TD>
  <TD><%=visitTimes%></TD>
  </TR>
  <TR>
  <TD></TD>
  <TD><INPUT type = "button" value="刷新" > </TD>
  </TR>
  </TABLE>
  </FORM>
  </body>




error.jsp(这段代码报的错)
这里的代码有点迷糊 执行顺序不是我想的那样
下面有return 那么return下面的语句应该都不执行了
<%=exception.getMessage()%>也应该不会执行 所以不会出现说
java.lang.NullPointerException的错误 应该是直接跳到check.jsp吧
可能是我理解错了 谁可以帮忙看下


 <body>
  <%
  //设置request编码方式,解决request请求中的中文乱码
  request.setCharacterEncoding("UTF-8");
  //设置response编码方式,解决response响应中的中文乱码
  response.setCharacterEncoding("UTF-8");
  if(request.getMethod().equals("post")){
  Cookie usernameCookie = new Cookie("username",request.getParameter("username"));
  Cookie visittimesCookie = new Cookie("visitTimes","0");
  response.addCookie(usernameCookie);
  response.addCookie(visittimesCookie);
  //显示cookie页面
  response.sendRedirect(request.getContex