-1

I am new to servlets. I have a class MenuServlet from where I call getMenu function of StoreController class. In this StoreController class I connected database and executed query. Hereby i attached two classes functions where it may be wrong. I checked the connection also. when i consoled there is no problem i can get the list of items. But i am getting null pointer exception.

Servlet.service() for servlet [jsp] threw exception
java.lang.NullPointerException
    at org.apache.jsp.menu_jsp._jspService(menu_jsp.java:102)
    at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:71)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:477)
    at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:395)
    at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:339)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:742)
    at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:484)
    at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:409)
    at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:337)
    at milkshake.servlets.MenuServlet.doGet(MenuServlet.java:63)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
//this is doget function of menuservlet
protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        response.setContentType("text/html");
        PrintWriter pw = response.getWriter();
        pw.println("menuservlet");

        StoreController sc = new StoreController();

        try {
            request.setAttribute("menu1", sc.getMenu());
        } catch (SQLException e) {
           e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        RequestDispatcher dispatcher = request.getRequestDispatcher("menu.jsp");
        dispatcher.forward(request, response);

    }
public class StoreController {
    static List<Milkshake> menuboard = new ArrayList<Milkshake>();
    public List<Milkshake> getMenu() throws SQLException,
            ClassNotFoundException {

        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

        String username = "sa";
        String password = "123456abcd";
        String url = "jdbc:sqlserver://localhost;databaseName=Milkshake";

        Connection con;

        con = DriverManager.getConnection(url, username, password);

        String sql = "select * from dbo.Milkshake";
        Statement stmt = con.createStatement();
        ResultSet rs = stmt.executeQuery(sql);
        while (rs.next()) {
            
            menuboard.add(new Milkshake(rs.getInt(1),rs.getString(2), rs.getDouble(3)));

        }
        rs.close();
        stmt.close();
        con.close();
        

        return menuboard;

    }

}
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h2>Menu</h2>
<h2>items:</h2>

<%List<Milkshake> list=(List<Milkshake>)request.getAttribute("menu1"); %>
<%for (Milkshake m:list){ %>

<%=m.getMilkshakeid()%>
<%=m.getName() %>
<%=m.getPrice() %>
<%} %>
<form action="AddServlet">
<button>addorder</button>
</form>
</body>
</html>

2 Answers2

1

Thank you for your responses. The reasons for null pointer exception while retrieving from the database are

  1. Mysql jar is not added to class path.
  2. Connection object is not properly initialised so the con object itself is null
  3. register and load driver class only once
  4. Null check the objects if you are not sure
0

Probably your server is failing to load the JDBC driver class. In order to confirm it, I would debug the servlet code or at least put System.out.println(sc.getMenu()) before request.setAttribute("menu1", sc.getMenu()).

Apart from this, I can see multiple issues with your code:

  1. In the JSP, the import statement is missing.
  2. It seems you have defined the servlet-mapping in web.xml. However, I recommend you use @WebServlet annotation which is much simpler to use and removes the need for an additional file (web.xml).
  3. You should not declare menuboard as static in StoreController. This way, you are making it a class variable which means the value of menuboard will be same for all instances of StoreController. If this variable is to be used by just getMenu() I recommend you make it local to getMenu().
  4. If you are closing Connection, you do not need to close Resultset and Statement explicitly. They will be automatically closed when the Connection is closed.

Given below is an mvce using MySQL database:

enter image description here

Milkshake.java:

package beans;

public class Milkshake {
    private int milkshakeid;
    private String name;
    private double price;

    public Milkshake(int milkshakeid, String name, double price) {
        this.milkshakeid = milkshakeid;
        this.name = name;
        this.price = price;
    }

    public int getMilkshakeid() {
        return milkshakeid;
    }

    public String getName() {
        return name;
    }

    public double getPrice() {
        return price;
    }
}

StoreController.java:

package milkshake.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import beans.Milkshake;

public class StoreController {
    public List<Milkshake> getMenu() throws SQLException, ClassNotFoundException {
        List<Milkshake> menuboard = new ArrayList<>();
        Class.forName("com.mysql.jdbc.Driver"); 
        Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/dbase", "root", "Hello@123");
        String sql = "select * from Milkshake";
        Statement stmt = con.createStatement();
        ResultSet rs = stmt.executeQuery(sql);
        while (rs.next()) {
            menuboard.add(new Milkshake(rs.getInt(1), rs.getString(2), rs.getDouble(3)));
        }
        con.close();
        return menuboard;
    }
}

AddServlet.java:

package servlets;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.RequestDispatcher;
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 milkshake.db.StoreController;

@WebServlet("/AddServlet")
public class AddServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        StoreController sc = new StoreController();
        try {
            request.setAttribute("menu1", sc.getMenu());
        } catch (SQLException | ClassNotFoundException e) {
            e.printStackTrace();
        }
        RequestDispatcher dispatcher = request.getRequestDispatcher("menu.jsp");
        dispatcher.forward(request, response);
    }
}

menu.jsp:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@page import="java.util.List,beans.Milkshake"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
    <h2>Menu</h2>
    <h2>items:</h2>

    <%
        List<Milkshake> list = (List<Milkshake>) request.getAttribute("menu1");
    %>
    <%
        for (Milkshake m : list) {
    %>

    <%=m.getMilkshakeid()%>
    <%=m.getName()%>
    <%=m.getPrice()%>
    <br>
    <%
        }
    %>
</body>
</html>

Output:

enter image description here

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
  • i pasted here parts of code not the full code so that you couldn't find imports or annotation. thanks. i got menu and items in h2 tag. i dont get list of items. my list of items is null. may be as you said my server is failing to load database. – Monisha Ravi Aug 03 '20 at 07:40