Domanda

I'm creating a simple Remember Me form using Jsp & Servlels . Here's my code :-

For new.jsp:-

<%
Cookie c[] = request.getCookies();
String v1 = "";
String v2 = "";

int i = 0;

for(i = 0 ; i < c.length ; i++)
{
  String ck = c[i].getName(); // NullPointerException
  if(ck == null)
  {
    v1 = "";
    v2 = "";
  }
  else if(ck.equals("userName"))
  {
    v1 = c[i].getValue();
  }
  else if(ck.equals("userPass"))
  {
    v2 = c[i].getValue();
  }
}
%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>JSP Page</title>
  </head>
  <body>
    <center>
      <h1>Remember Me</h1>
      <hr>
      <form action="Rem" method="post">
        Enter name : <input type="name" name="user" value=<%=v1%>>
        Enter password : <input type="password" name="pass" value=<%=v2%>>
        <input type="submit" value="Login"><br>
        <input type="checkbox" name="me" value="yes">Remember Me
      </form>
    </center>  
  </body>
</html>

for Rem.java:-

  PrintWriter out = response.getWriter();
  String user = request.getParameter("user");
  String pass = request.getParameter("pass");
  String me = request.getParameter("me");
  int flag = 0;
  if("batman".equals(user) && "batman".equals(pass) && me != null)
  {
    flag = 1;
    Cookie userName = new Cookie("userName" , user);
    Cookie userPass = new Cookie("userPass" , pass);
    userName.setMaxAge(60*60*24*7);
    userPass.setMaxAge(60*60*24*7);
    response.addCookie(userName);
    response.addCookie(userPass);

    response.sendRedirect("wel.html");
  }
  else if("batman".equals(user) && "batman".equals(pass) && me == null)
  {
    flag = 1;
    response.sendRedirect("wel.html");
  }

  if(flag == 0)
  {
    RequestDispatcher dis = request.getRequestDispatcher("new.jsp");
    out.println("<center><h4>Please enter correct username or password</h4</center<hr>");
    dis.include(request, response);
  }

But whenever I run it , I get a NullPointerException(location marked above).The new.jsp is the first page that is run . Could that be a problem . But I've already checked for null . What could be the problem ? Please help ! Fast !!

Thank You !

È stato utile?

Soluzione

Are you sure the exception is inside the for loop because i think it should be in c.length call..

The scriptlet in your jsp gets your server's cookies from the client:

Cookie[] cookies = request.getCookies();

but on the initial request, there are no cookies set by your server on any given client, so getCookies() returns null in accordance with the servlet spec.

Put an "if" statement around your "for" loop to check if cookies is null or not and that should fix your problem.

if(cookies != null) {
    for (int i=0; i<cookies.length; i++) {
    ...
    }
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top