My small project uses a database table that contains data about employees(name, phone, email). It provides front-end managment(insert news employee, edit current, remove existing) of the list of employees via a web browser.
Whenever I run my project(to display the list of all employees) on the Tomcat server from Eclipse I get the following error:
java.lang.NullPointerException
com.myproject.crud.EmployeesListServlet.doGet(EmployeesListServlet.java:24)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
Line 24: request.setAttribute("employeess", employeesRepo.listEmployeess());
EmployeesListServlet
package com.myproject.crud;
import java.io.IOException;
import javax.inject.Inject;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@SuppressWarnings("serial")
@WebServlet("/employees/")
public class EmployeesListServlet extends HttpServlet {
@Inject @JDBC
private EmployeesRepository employeesRepo;
public EmployeesListServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setAttribute("employeess", employeesRepo.listEmployeess());
getServletContext().getRequestDispatcher("/WEB-INF/pages/employees-listing.jsp").forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
Your previous question confirms that you were trying to follow this tutorial. It is however targeted on Caucho Resin, a full fledged Java EE application server which supports all the Java EE fanciness out the box without the need to add some more JARs.
You, however, are using Tomcat. Tomcat is a barebones JSP/Servlet container which doesn’t support all the other Java EE fanciness out the box. It supports only JSP and Servlets. The
@Inject, which is part of the CDI, wouldn’t have been importable in your Java servlet code in first place. That you got it to compile can only mean that you downloaded some JAR containingjavax.inject.Injectand dropped it in runtime classpath.This isn’t the way how to install CDI in Tomcat. You’d need to do a bit more work. See also among others Weld (the CDI reference implementation) documentation on Tomcat.
I would however recommend to stop reading that tutorial, it isn’t exactly a very nice introdcuction to Java EE (the
@JDBCannotation is at its own also somewhat a “wtf?”) and look for another tutorial, or better, a real book. If you want seriously learn Java EE, then I’d also recommend to replace Tomcat by a real Java EE application server, such as TomEE, Glassfish, JBoss AS, etc. They all ship with CDI out the box (and JPA and EJB which are way much better than JDBC).