簡體   English   中英

JSP Servlet Web 應用程序

[英]JSP Servlet Web Application

我目前正在開發一個 Web 應用程序,但它不起作用。 下面是迄今為止我為 servlet 和 Java 類編寫的代碼。 我檢查了提供數據庫連接的代碼,我知道這是正確的。 我相信 servlet 或 Java 類有問題。

這是我收到的錯誤:

HTTP Status 500 -

type Exception report

message

description The server encountered an internal error that prevented it from fulfilling this request.

exception

java.lang.NullPointerException
    music.data.ConnectionPool.freeConnection(ConnectionPool.java:41)
    music.data.ProductDB.selectProducts(ProductDB.java:159)
    music.admin.ProductAdminController.displayProducts(ProductAdminController.java:74)
    music.admin.ProductAdminController.doGet(ProductAdminController.java:36)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:618)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)

這是 Java Servlet:

package music.admin;

import java.io.IOException;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import music.business.Product;
import music.data.ProductDB;

public class ProductAdminController extends HttpServlet {

    /* Comment this method out when using this class with a database
     * instead of a text file.
     */
    //@Override
    //public void init() {
        //ProductIO.init(getServletContext()
               // .getRealPath("/WEB-INF/products.txt"));
    //}

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        // get current action
        String action = request.getParameter("action");
        if (action == null) {
            action = "displayProducts";  // default action
        }

        // perform action and set URL to appropriate page
        String url = "/index.jsp";
        if (action.equals("displayProducts")) {
            url = displayProducts(request, response);
        } else if (action.equals("displayProduct")) {
            url = displayProduct(request, response);
        } else if (action.equals("addProduct")) {
            url = "/product.jsp";
        } else if (action.equals("deleteProduct")) {
            url = deleteProduct(request, response);
        }
        getServletContext()
                .getRequestDispatcher(url)
                .forward(request, response);
    }

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        // get current action
        String action = request.getParameter("action");
        if (action == null) {
            action = "displayProducts";  // default action
        }

        // perform action and set URL to appropriate page
        String url = "/index.jsp";
        if (action.equals("updateProduct")) {
            url = updateProduct(request, response);
        } else if (action.equals("deleteProduct")) {
            url = deleteProduct(request, response);
        }
        getServletContext()
                .getRequestDispatcher(url)
                .forward(request, response);
    }

    private String displayProducts(HttpServletRequest request,
            HttpServletResponse response) {

        ArrayList<Product> products = (ArrayList) ProductDB.selectProducts();
        request.setAttribute("products", products);
        return "/products.jsp";
    }

    private String displayProduct(HttpServletRequest request,
            HttpServletResponse response) {

        String productCode = request.getParameter("productCode");
        Product product;
        if (productCode == null || productCode.isEmpty()) {
            product = new Product();
        } else {
            product = ProductDB.selectProduct(productCode);
        }

        request.setAttribute("product", product);
        return "/product.jsp";
    }

    private String addProduct(HttpServletRequest request,
            HttpServletResponse response) {

        return "/product.jsp";
    }

    private String updateProduct(HttpServletRequest request,
            HttpServletResponse response) {

        String productCode = (String) request.getParameter("productCode");
        String description = (String) request.getParameter("description");
        String priceString = (String) request.getParameter("price");

        double price;
        try {
            price = Double.parseDouble(priceString);
        } catch (NumberFormatException e) {
            price = 0;
        }

        Product product = (Product) request.getAttribute("product");
        if (product == null) {
            product = new Product();
        }
        product.setCode(productCode);
        product.setDescription(description);
        product.setPrice(price);
        request.setAttribute("product", product);

        String message = "";
        if (product.getPrice() <= 0) {
            message = "You must enter a positive number for the price without "
                    + "any currency symbols.";
        }
        if (product.getDescription().length() == 0) {
            message = "You must enter a description for the product.";
        }
        if (product.getCode().length() == 0) {
            message = "You must enter a code for the product.";
        }
        request.setAttribute("message", message);

        String url;
        if (message.isEmpty()) {
            if (ProductDB.exists(product.getCode())) {
                ProductDB.updateProduct(product);
            } else {
                ProductDB.insertProducts(product);
            }
            url = displayProducts(request, response);
        } else {
            url = "/product.jsp";
        }
        return url;
    }

    private String deleteProduct(HttpServletRequest request,
            HttpServletResponse response) {

        String productCode = request.getParameter("productCode");
        Product product = ProductDB.selectProduct(productCode);
        request.setAttribute("product", product);

        String url;
        String yesButton = request.getParameter("yesButton");
        if (yesButton != null) {
            ProductDB.removeProduct(product);
            url = displayProducts(request, response);
        } else {
            url = "/confirm_product_delete.jsp";
        }
        return url;
    }    
}

這是Java類:

package music.data;

import java.sql.*;
import java.util.*;

import music.business.Product;

public class ProductDB
{
    //This method returns null if a product isn't found.
    public static Product selectProduct(String productCode)
    {
        ConnectionPool pool = ConnectionPool.getInstance();
        Connection connection = pool.getConnection();
        PreparedStatement ps = null;
        ResultSet rs = null;

        String query = "SELECT * FROM Product " +
                "WHERE ProductCode = ?";
        try
        {
            ps = connection.prepareStatement(query);
            ps.setString(1, productCode);
            rs = ps.executeQuery();
            if (rs.next())
            {
                Product p = new Product();

                p.setCode(rs.getString("ProductCode"));
                p.setDescription(rs.getString("ProductDescription"));
                p.setPrice(rs.getDouble("ProductPrice"));
                return p;
            }
            else
            {
                return null;
            }
        }
        catch(SQLException e)
        {
            System.out.println(e);
            return null;
        }
        finally
        {
            DBUtil.closeResultSet(rs);
            DBUtil.closePreparedStatement(ps);
            pool.freeConnection(connection);
        }
    }

    //This method will return 0 if productID isn't found.
    public static int selectProductID(Product product)
    {
        ConnectionPool pool = ConnectionPool.getInstance();
        Connection connection = pool.getConnection();
        PreparedStatement ps = null;
        ResultSet rs = null;

        String query = "SELECT ProductID FROM Product " +
                "WHERE ProductCode = ?";
        try
        {
            ps = connection.prepareStatement(query);
            ps.setString(1, product.getCode());
            rs = ps.executeQuery();
            rs.next();
            int productID = rs.getInt("ProductID");
            return productID;
        }
        catch(SQLException e)
        {
            System.out.println(e);
            return 0;
        }
        finally
        {
            DBUtil.closeResultSet(rs);
            DBUtil.closePreparedStatement(ps);
            pool.freeConnection(connection);
        }
    }

    //This method returns null if a product isn't found.
    public static Product selectProduct(int productID)
    {
        ConnectionPool pool = ConnectionPool.getInstance();
        Connection connection = pool.getConnection();
        PreparedStatement ps = null;
        ResultSet rs = null;

        String query = "SELECT * FROM Product " +
                "WHERE ProductID = ?";
        try
        {
            ps = connection.prepareStatement(query);
            ps.setInt(1, productID);
            rs = ps.executeQuery();
            if (rs.next())
            {
                Product p = new Product();
                p.setCode(rs.getString("ProductCode"));
                p.setDescription(rs.getString("ProductDescription"));
                p.setPrice(rs.getDouble("ProductPrice"));
                return p;
            }
            else
            {
                return null;
            }
        }
        catch(SQLException e)
        {

            System.out.println(e);
            return null;
        }
        finally
        {
            DBUtil.closeResultSet(rs);
            DBUtil.closePreparedStatement(ps);
            pool.freeConnection(connection);
        }
    }

    //This method returns null if a product isn't found.
    public static ArrayList<Product> selectProducts()
    {
        ConnectionPool pool = ConnectionPool.getInstance();
        Connection connection = pool.getConnection();
        PreparedStatement ps = null;
        ResultSet rs = null;

        String query = "SELECT * FROM Product";
        try
        {
            ps = connection.prepareStatement(query);
            rs = ps.executeQuery();
            ArrayList<Product> products = new ArrayList<Product>();
            while (rs.next())
            {
                Product p = new Product();
                p.setCode(rs.getString("ProductCode"));
                p.setDescription(rs.getString("ProductDescription"));
                p.setPrice(rs.getDouble("ProductPrice"));
                products.add(p);
            }
            return products;
        }
        catch(SQLException e)
        {
           System.out.println(e);
            return null;
        }
        finally
        {
            DBUtil.closeResultSet(rs);
            DBUtil.closePreparedStatement(ps);
            pool.freeConnection(connection);
        }
    }    



public static void insertProducts(Product product)
    {
        ConnectionPool pool = ConnectionPool.getInstance();
        Connection connection = pool.getConnection();
        PreparedStatement ps = null;
        ResultSet rs = null;

        String query = "INSERT INTO product (ProductCode, ProductDescription, ProductPrice)"
                + "VALUES"
                + "('"+product.getCode()+"','"+product.getDescription()+"','"+product.getPriceNumberFormat()+"');";
        try
        {
            ps = connection.prepareStatement(query);
           ps.execute(query);


        }
        catch(SQLException e)
        {
            System.out.println(e);

        }
        finally
        {
            DBUtil.closeResultSet(rs);
            DBUtil.closePreparedStatement(ps);
            pool.freeConnection(connection);
        }
    } 

public static void updateProduct(Product product)
    {
        ConnectionPool pool = ConnectionPool.getInstance();
        Connection connection = pool.getConnection();
        PreparedStatement ps = null;
        ResultSet rs = null;



        String query = "UPDATE product SET productDescription ='"+product.getDescription()+"',"+"ProductPrice='"+product.getPriceNumberFormat()+"' WHERE ProductCode='"+product.getCode()+"';";

        try
        {
            ps = connection.prepareStatement(query);
            ps.execute(query);
            //rs = ps.executeQuery();


        }
        catch(SQLException e)
        {
            System.out.println(e);

        }
        finally
        {
            DBUtil.closeResultSet(rs);
            DBUtil.closePreparedStatement(ps);
            pool.freeConnection(connection);
        }
    }


    public static boolean exists(String productCode) {
        ConnectionPool pool = ConnectionPool.getInstance();
        Connection connection = pool.getConnection();
        PreparedStatement ps = null;
        ResultSet rs = null;

        String query = "SELECT productCode FROM Product " +
                "WHERE ProductCode = ?";
        try {
            ps = connection.prepareStatement(query);
            ps.setString(1, productCode);
            rs = ps.executeQuery();
            return rs.next();
        } catch (SQLException e) {
            System.out.println(e);
            return false;
        } finally {
            DBUtil.closeResultSet(rs);
            DBUtil.closePreparedStatement(ps);
            pool.freeConnection(connection);
        }
    }

public static void removeProduct(Product product)
    {
        ConnectionPool pool = ConnectionPool.getInstance();
        Connection connection = pool.getConnection();
        PreparedStatement ps = null;
        ResultSet rs = null;

        String query = "DELETE FROM product WHERE ProductCode='"+product.getCode()+"';";
        try
        {
            ps = connection.prepareStatement(query);
           ps.execute(query);


        }
        catch(SQLException e)
        {
           System.out.println(e);

        }
        finally
        {
            DBUtil.closeResultSet(rs);
            DBUtil.closePreparedStatement(ps);
            pool.freeConnection(connection);
        }
    } 

}

這是連接池的代碼:

package music.data;


import java.sql.*;
import javax.sql.DataSource;
import javax.naming.InitialContext;
import javax.naming.NamingException;

public class ConnectionPool {

    private static ConnectionPool pool = null;
    private static DataSource dataSource = null;

    private ConnectionPool() {
        try {
            InitialContext ic = new InitialContext();
            dataSource = (DataSource) ic.lookup("java:/comp/env/jdbc/music");
        } catch (NamingException e) {
            System.out.println(e);
        }
    }

    public static synchronized ConnectionPool getInstance() {
        if (pool == null) {
            pool = new ConnectionPool();
        }
        return pool;
    }

    public Connection getConnection() {
        try {
            return dataSource.getConnection();
        } catch (SQLException e) {
            System.out.println(e);
            return null;
        }
    }

    public void freeConnection(Connection c) {
        try {
            c.close();
        } catch (SQLException e) {
            System.out.println(e);
        }
    }
}

DBUtil 類

package music.data;

import java.sql.*;

public class DBUtil
{
    public static void closeStatement(Statement s)
    {
        try
        {
            if (s != null)
                s.close();
        }
        catch(SQLException e)
        {
            e.printStackTrace();
        }
    }

    public static void closePreparedStatement(Statement ps)
    {
        try
        {
            if (ps != null)
                ps.close();
        }
        catch(SQLException e)
        {
            e.printStackTrace();
        }
    }

    public static void closeResultSet(ResultSet rs)
    {
        try
        {
            if (rs != null)
                rs.close();
        }
        catch(SQLException e)
        {
            e.printStackTrace();
        }
    }
}

從你的問題和提供的代碼來看,我認為有幾點可以重新審視,看看我們是否有任何問題。

  1. 您已使用 DBUtil 類關閉結果集和語句對象。

    • DBUtil 似乎不是標准類。 使用來自 apache 的 DBUtils 可能是更好的選擇。 鑒於 DBUtil 似乎沒有標准實現,請提供 DBUtil 的實現以及其他類。

    • 此外,使用 DButil 關閉結果集和語句會丟失對稱性,但使用其他一些方法關閉連接。 我建議使用 DBUtils.close() 或 closequietly() 來關閉連接。

  2. 此外,在您的實現中,初始連接池大小似乎不清楚。 通過使用 ds.setInitialPoolSize() 將 poolsize 顯式設置為更高的數字。

    • 此外,如果需要,設置 maximumPoolsize 和 preferredPoolSize。

這樣做應該主要解決問題,或者明確問題。

既然您已經發布了代碼,問題就很清楚了:您得到 NullPointerException,因為您試圖在空連接上調用close()

為什么連接為空?

因為 getConnection() 方法返回 null:

    try {
        return dataSource.getConnection();
    } catch (SQLException e) {
        System.out.println(e);
        return null;
    }

在上面的代碼中,您嘗試從 DataSource 獲取連接,如果數據源通過拋出異常表示您無法獲取連接,則您基本上忽略該異常,而是返回 null。

結果:不是得到一個明確的 SQLException 來解釋為什么你不能從 DataSource 獲得連接,而是在一個不相關的方法中得到一個模糊的 NullPointerException,它沒有告訴你任何關於實際問題的信息。

不要那樣做。 如果您在調用getConnection()時確實不想處理已檢查的 SQLException,則將 SQLException 包裝到運行時異常中。 然后,您將獲得清晰的消息和堆棧跟蹤指示問題的真正所在和位置:

    try {
        return dataSource.getConnection();
    } catch (SQLException e) {
        throw new RuntimeSQLException(e);
    }

public class RuntimeSQLException extends RuntimeException {
    public RuntimeSQLException(Throwable cause) {
        super(cause);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM