Ive tried everything and i cant seem to figure why i keep getting "list is null" when i run my jsp file. Here is my servlet file
package servlet;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import model.Question;
@WebServlet("/DrivingTestBrowser")
public class DrivingTestBrowser extends HttpServlet {
private static final long serialVersionUID = 1L;
public void init(ServletConfig config) throws ServletException {
super.init(config);
List<Question> entry = new ArrayList<>();
ServletContext context = getServletContext();
String file = getServletContext().getRealPath("/WEB-INF/Drivingtest.txt");
Scanner in = new Scanner(file);
while (in.hasNextLine()){
Question question = new Question();
question.setDescription(in.nextLine());
question.setAnswerA(in.nextLine());
question.setAnswerB(in.nextLine());
question.setAnswerC(in.nextLine());
question.setCorrectAnswer(Integer.parseInt(in.nextLine()));
in.nextLine();
entry.add(question);
}
in.close();
context.setAttribute("entries", entry);
}
public DrivingTestBrowser() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
int id;
HttpSession session = request.getSession();
if (session.getAttribute("id") == null) {
id = 0;
} else {
id = (int) session.getAttribute("id");
id++;
}
session.setAttribute("id", id);
request.setAttribute("SessionID", id);
request.getRequestDispatcher("DrivingTestBrowser.jsp").forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
and this is my jsp file
<%@page import="java.util.List"%>
<%@page import="model.Question"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>DrivingTestBrowser</title>
</head>
<body>
<%
ServletContext context = request.getServletContext();
List<Question> list = (List<Question>)context.getAttribute("entries");
int Sessionid = 0;
if (request.getAttribute("Sessionid")!= null) {
Sessionid = Integer.parseInt(request.getAttribute("Sessionid").toString())% list.size();
}
%>
<p><%=list.get(Sessionid).getDescription()%></p>
<p>1:<%=list.get(Sessionid).getAnswerA()%></p>
<p>2:<%=list.get(Sessionid).getAnswerB()%></p>
<p>3:<%=list.get(Sessionid).getAnswerC()%></p>
<p>Correct Answer:<%=list.get(Sessionid).getCorrectAnswer()%></p>
<p><a href="DrivingTestBrowser?Sessionid=<%=Sessionid++%>">Next</a></p>
</body>
</html>
This is the error im getting "java.lang.NullPointerException: Cannot invoke "java.util.List.get(int)" because "list" is null"
My list of questions is null