0

I was trying to get the values (List productList = data.getProductList();) in ShowProductCatalog.jsp from the JavaBean ProductDataBean.java. I'm getting the error nullpointerexception. Please help! Your help will be much appreciated.

*edited: I realised the connection I'm getting in ProductDataBean.java in getProductList() is null. Now the question is, how can I make the changes to insert the value? If I put the whole connection in getProductList(), there is error message. "No Suitable Driver found."

      **ShowProductCatalog.jsp**


    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
     pageEncoding="ISO-8859-1"%>
     <%@ page import = "java.util.*" import="cart.*,java.net.*,java.text.*"%>
     <jsp:useBean id="data" scope="session" class="cart.ProductDataBean" />

      <!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">
</head>
<body>
    <%
        List productList = data.getProductList();
        Iterator prodListIterator = productList.iterator();
        %>



      **ProductDataBean.java**


package cart;
import java.io.*;
import java.sql.*;
import java.util.*;
public class ProductDataBean implements Serializable{

    private static Connection connection;
    private PreparedStatement addRecord, getRecords;

    public ProductDataBean(){
        try{
            // Step1: Load JDBC Driver
            Class.forName("com.mysql.jdbc.Driver");
            // Step 2: Define Connection URL
            String connURL ="jdbc:mysql://localhost/onlineshop?user=root&password=teck1577130713"; 
            // Step 3: Establish connection to URL
            connection =   DriverManager.getConnection(connURL);
        }catch(Exception e){e.printStackTrace();}
    }
    public static Connection getConnection(){
        return connection;
    }
    public ArrayList getProductList() throws SQLException{
        ArrayList productList = new ArrayList();
        Statement statement = connection.createStatement();
        ResultSet results = statement.executeQuery("SELECT * FROM products");
        while (results.next()){
            DVD movie = new DVD();
            movie.setMovie(results.getString("movieName"));
            movie.setRating(results.getString("movieRate"));
            movie.setYear(results.getString("movieYear"));
            movie.setPrice(results.getDouble("moviePrice"));
            productList.add(movie);
        }
        return productList;
    }
}
De De De De
  • 326
  • 3
  • 10
  • 31

2 Answers2

0

Your JSP page is working properly and there is no mistake. Check your database and confirm that you have rows inside the products table. Null pointer exception occurs because the method getProductList() is not returning an ArrayList.

user987339
  • 10,519
  • 8
  • 40
  • 45
  • I realised the connection I'm getting in ProductDataBean.java in getProductList() is null. Now the question is, how can I make the changes to insert the value? If I put the whole connection in getProductList(), there is error message – De De De De Feb 08 '14 at 11:57
  • Something like "No suitable driver found" – De De De De Feb 08 '14 at 11:58
0

Check your build path mySql driver is added. and please add exception to the question what you getting, then easily can answer.

mysql-connector-java-5.1.24-bin.jar

you can get it from here

have a look this SO How to avoid java code in jsp

I suggest you to use Servlets instead of writing java code in jsp. If you write code in servlets then easily you can test/debug your code.

To answer: how can I make the changes to insert the value?

Create a PreparedStatement obj with sql insert query and call [executeUpdate()][3] to perform INSERT, UPDATE or DELETE operations.

Add this piece of code in your ProductDataBean class to add a new record to table.

    public static void addRecord(DVD dvd) throws SQLException{
                PreparedStatement pStatement = 
getConnection().prepareStatement("insert into products(movieName, movieRate, movieYear, moviePrice) values(?,?,?,?)");
                pStatement.setString(1, dvd.getMovie());
                pStatement.setString(2, dvd.getRating());
                pStatement.setString(3, dvd.getYear());
                pStatement.setDouble(4, dvd.getPrice());
                pStatement.executeUpdate();
            }

Make your DVD class a POJO like

package cart;

public class DVD {

    private String movie;
    private String rating;
    private String year;
    private Double price;

    public DVD(){}  

    public DVD(String movie, String rating, String year, Double price) {        
        this.movie = movie;
        this.rating = rating;
        this.year = year;
        this.price = price;
    }



    public String getMovie() {
        return movie;
    }

    public void setMovie(String movie) {
        this.movie = movie;
    }

    public String getRating() {
        return rating;
    }

    public void setRating(String rating) {
        this.rating = rating;
    }

    public String getYear() {
        return year;
    }

    public void setYear(String year) {
        this.year = year;
    }

    public Double getPrice() {
        return price;
    }

    public void setPrice(Double price) {
        this.price = price;
    }

    @Override
    public String toString() {
        return "DVD [movie=" + movie + ", rating=" + rating + ", year=" + year
                + ", price=" + price + "]";
    }

}

And in your jsp page call servlet url pattern to perform GET and POST, and to render all products in jsp user standard tag lib jstl1.2.jar you get it from here So replace your jsp file with:

<%@ 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 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">
</head>
<body>
<c:url value="/Product" var="pdctServletUrl"/>
Product Page
<form method="post" action="${pdctServletUrl}">
    <h4>Enter New Movie details:</h4>

    <label>Name</label>
    <input type="text" name="movie"/>

    <label>Rating</label>
    <input type="text" name="rating"/>

    <label>Year</label>
    <input type="text" name="year"/>

    <label>Price</label>
    <input type="text" name="price"/>

    <input type="submit" value="save movie"/>
</form>
<br/>
To get a list of products click 
<a href="${pdctServletUrl}">Get Products</a>   

<c:if test="${not empty products}">
<h4>Available Products.</h4>
<table>
    <tr>
        <th>Movie Name</th>
        <th>Rating</th>
        <th>Year</th>
        <th>Price</th>
    </tr>
    <c:forEach items="${products}" var="pd">
        <tr>
            <td>${pd.movie}</td>
            <td>${pd.rating}</td>
            <td>${pd.year}</td>
            <td>${pd.price}</td>
        </tr>
    </c:forEach>
</table>
</c:if>

</body>
</html>

A servlet to handle GET and POST request's and transfering data to client etc.

Product.java

package cart;

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

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class Product
 */
@WebServlet("/Product")
public class Product extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private ProductDataBean pDataBean = new ProductDataBean();

    public Product() {
        super();        
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        List<Product> products;
        try {
            products = pDataBean.getProductList();  // Obtain all products.
            request.setAttribute("products", products); // Store products in request scope.
            request.getRequestDispatcher("/test.jsp").forward(request, response); // Forward to JSP page to display them in a HTML table.
        } catch (SQLException e) {                  
            e.printStackTrace();
        }
    }

    /* (non-Javadoc)
     * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {  
        String movie = req.getParameter("movie");
        String rating = req.getParameter("rating");
        String year = req.getParameter("year");
        Double price = Double.valueOf(req.getParameter("price"));

        if(movie!=null && rating!=null && year!=null && price!=null)
            try {
                ProductDataBean.addRecord(new DVD(movie, rating, year, price));
            } catch (SQLException e) { 
                e.printStackTrace();
            }
        doGet(req, resp);
    }

}

I think this may help you to understand.

Community
  • 1
  • 1
Abhishek Nayak
  • 3,732
  • 3
  • 33
  • 64
  • HTTP Status 500 - java.lang.NullPointerException message java.lang.NullPointerException description The server encountered an internal error that prevented it from fulfilling this request. exception org.apache.jasper.JasperException: java.lang.NullPointerException org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:549) – De De De De Feb 08 '14 at 12:10
  • did you use any IDE like eclipse ? – Abhishek Nayak Feb 08 '14 at 12:45
  • @De De De De clean your server work directory and restart server, re run your application. – Abhishek Nayak Feb 08 '14 at 13:03
  • 1
    Wow. Thanks for your time and effort to write this post. – De De De De Feb 08 '14 at 14:41