我試圖做一個非常簡單的登錄屏幕。它必須檢查密碼和用戶名。還有一個默認用戶,在init()
中設置。奇怪的是,它仍然給我NullPointerException
rd.forward();
有人可以解釋一下嗎?我很抱歉我的英語不好,讓我知道是否需要詳細說明。Javaservlet nullpointerexception
package servlets;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Scanner;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import classes.user;
public class loginServlet extends HttpServlet {
ArrayList<user> alleUsers = new ArrayList<>();
private String defaultUser="", defaultPassword="";
private user userding;
public void init(ServletConfig config) throws ServletException{
super.init(config);
defaultUser = config.getInitParameter("defaultUser");
defaultPassword = config.getInitParameter("defaultPassword");
user userding = new user(defaultUser, defaultPassword);
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String a = req.getParameter("back");
String b = req.getParameter("username");
String c = req.getParameter("password");
Object o = getServletContext().getAttribute("arraylist");
RequestDispatcher rd = null;
if (a.equals("Register")) {
rd = req.getRequestDispatcher("registerScherm.jsp");
}
if (a.equals("Login")) {
System.out.println(b + " "+ c);
if(!b.equals(null) && !c.equals(null)){
if (o instanceof ArrayList) {
alleUsers = (ArrayList) o;
alleUsers.add(userding);
if (alleUsers != null) {
for (user u : alleUsers) {
if (b.equals(u.getUsername()) && c.equals(u.getPassword())) {
getServletContext().setAttribute("naam", b);
rd = req.getRequestDispatcher("ingelogdScherm.jsp");
break;
} else {
rd = req.getRequestDispatcher("loginScherm.jsp");
}
}
}
}
}else{
rd = req.getRequestDispatcher("loginScherm.jsp");
}
}
rd.forward(req, resp);
//It gives an error on this forward
}
}
這裏是我的loginscreen jsp頁面:
<body>
<%
String userName = "";
for (Cookie c : request.getCookies()) {
if (c.getName().equals("username")) {
userName = c.getValue();
break;
}
}
%>
<div id="account">
<div id="inputbox">
<form action="loginServlet.do" method="post">
<input class="ltf" type="text" name="username" value="<%= userName %>" /><br/>
<input class="ltf" type="password" name="password" /><br/>
<input type="submit" name="back" value="Login" />
<input type="submit" name="back" value="Register" />
</form>
</div>
好吧,我想我固定它。我刪除了一些警衛,這有所幫助。我仍然困惑爲什麼它沒有通過他們,但它現在起作用。謝謝!
rd.forward(req, resp);
這可能是爲什麼你得到一個NullPointerException異常的原因,RD尚未初始化並沒有得到:
您可以顯示堆棧跟蹤? – Stultuske
你在'if'嵌套條件中初始化你的'RequestDispatcher'。有可能是未初始化的路徑。你應該自己調試一下。 – Mena
但如果這些字段爲空,它不應該在那裏初始化? – RandomStranger