0

i am trying to Retrieving Data from my data base named id and it has a 2 columns uname and pass. i believe my beans class which is student is fine totally and as you can see pol class is for interacting with db and class dispach send the data to jsp,my problem is than when i am runing dispach on server i get the NullPointerException

public class pol {

    public List<student> getstudent() throws Exception {

        List<student> students = new ArrayList<>();
        String connectionURL = "jdbc:mysql://localhost:3306/pooya";

        Connection connection = null;
        Statement s = null;
        ResultSet rs = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");

            connection = DriverManager.getConnection(connectionURL, "root", "");

            String sql = "select * from id";

            s = connection.createStatement();
            s.executeQuery(sql);

            rs = s.getResultSet();

            while (rs.next()) {

                String uname = rs.getString("uname");
                String pass = rs.getString("pass");
                student tempstudent = new student(uname, pass);
                students.add(tempstudent);

            }
            return students;

        } finally {
            // close JDBC objects
            close(connection, s, rs);
        }
    }

    private void close(Connection connection, Statement s, ResultSet rs) {

        try {
            if (rs != null) {
                rs.close();
            }

            if (s != null) {
                s.close();
            }

            if (connection != null) {
                connection.close();   // doesn't really close it ... just puts back in connection pool
            }
        } catch (Exception exc) {
            exc.printStackTrace();
        }
    }
}

public class dispach extends HttpServlet {
    private java java;
    private pol pol;

    @Resource(name = "jdbc/web_student_tracker")
    private DataSource dataSource;

    @Override
    public void init() throws ServletException {
        try {
            java = new java(dataSource);
        } catch (Exception exc) {
            throw new ServletException(exc);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            listteacher(request, response);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void listteacher(HttpServletRequest request, HttpServletResponse response) throws Exception {

        List<student> student = pol.getstudent();
        request.setAttribute("select", student);
        //fix
        RequestDispatcher dispatcher = request.getRequestDispatcher("/NewFile.jsp");

        dispatcher.forward(request, response);
    }
}

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<!DOCTYPE html>
<html>
<head>
    <meta charset="ISO-8859-1">
    <title>Insert title here</title>
</head>
<body>
<table>
    <c:forEach var="tempstudent" items="${select}">
        <tr>
            <td>${tempstudent.uname}</td>
        </tr>
    </c:forEach>
</table>
</body>
</html>

4
  • When asking for help about an exception, include the stack trace. In particular, point out which line it matches to in your pastes. Also, exceptions have 4 useful bits of info: Type, message, trace, cause. By going 'e.printStackTrace()' you are chucking 3 out of the 4 useful things, so stop doing this, it is a sign of bad code and makes finding causes of problems very difficult. If you don't know how to handle one, the fallback is 'throw new RuntimeException(e)', NOT 'e.printStackTrace()'. Commented Dec 1, 2019 at 18:51
  • thanks for your comment i changed my code as you said and now this is what i got 'SEVERE: Servlet.service() for servlet [response.dispach] in context with path [/table] threw exception'. in class dispach line 44 it throws exceptions Commented Dec 1, 2019 at 18:58
  • If you stop writing e.printStackTrace() everywhere, you'd get actual info about what went wrong and where it happened. Here's a good rule of thumb: Until you've been programming java for 2 years or more, you are not allowed to write the letters 'printStackTrace'. ever. no excuses. Commented Dec 1, 2019 at 19:01
  • i understood your point but i am lost about where should i start to debug it? Commented Dec 1, 2019 at 19:03

1 Answer 1

1

You are using the pol member variable in this line List<student> student = pol.getstudent(); in dispatch#listteacher method, but it has not yet been initialized. You have to initialize it first (in constructor, or some other way) to be able to call methods on it, else you will indeed get a NullPointerException.

Also consider to name your classes kebab-cased, e.g. Dispatch instead of dispatch. That is the Java class naming convention.

Sign up to request clarification or add additional context in comments.

6 Comments

can you tell em how can i initialize it?
You can do this.pol = new pol(); in your init method in the dispatch class (just as you do with the java member variable).
it works! i have the value of my table on display but my data suppose to go to my jsp file which is NewFile.jsp. when i run the dispach class the url is still on servlet not on jsp. could you please tell me what is wrong?
I'm sorry, this could be because of many things. Are you using servlets for a specific reason? If not, I would suggest to getting into learning a framework like Spring MVC or Spring Boot. With Spring Boot it's pretty simple to setup a basic Model View Controller example that just runs almost out-of-the-box (see spring.io/guides/gs/serving-web-content for more information). If you have to use servlets for whatever reason, then I would suggest asking a new question with example code etc. provided.
i am doing a student project with servlet but as soon as possible i will shift to spring . do you think learning servlet deeply is import for starting a spring framework?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.