【问题标题】:Java MVC JSP get Connection and Values from JavaBeanJava MVC JSP 从 JavaBean 获取连接和值
【发布时间】:2014-02-08 11:02:31
【问题描述】:

我试图从 JavaBean ProductDataBean.java 中获取 ShowProductCatalog.jsp 中的值 (List productList = data.getProductList();)。我收到错误空指针异常。请帮忙!非常感谢您的帮助。

*已编辑:我意识到我在 getProductList() 中的 ProductDataBean.java 中获得的连接为空。现在的问题是,如何进行更改以插入值?如果我将整个连接放在 getProductList() 中,则会出现错误消息。 “未找到合适的驱动程序。”

      **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;
    }
}

【问题讨论】:

    标签: java jsp model-view-controller get connection


    【解决方案1】:

    检查您的构建路径 mySql 驱动程序是否已添加。并请在您得到的问题中添加例外,然后可以轻松回答。

    mysql-connector-java-5.1.24-bin.jar
    

    你可以从here得到它

    看看这个 SO How to avoid java code in jsp

    我建议你使用Servlets,而不是用jsp写java代码。 如果您在 servlet 中编写代码,那么您可以轻松地测试/调试您的代码。

    回答:how can I make the changes to insert the value?

    使用 sql 插入查询创建 PreparedStatement obj 并调用 [executeUpdate()][3] 以执行 INSERTUPDATEDELETE 操作。

    在您的ProductDataBean 类中添加这段代码以将新记录添加到表中。

        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();
                }
    

    让你的 DVD 类像 POJO 一样

    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 + "]";
        }
    
    }
    

    并且在您的 jsp 页面中调用 servlet url 模式来执行 GET 和 POST,并在 jsp 用户标准标签库 jstl1.2.jar 中呈现所有产品,您可以从 here 获得它 因此,将您的 jsp 文件替换为:

    <%@ 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>
    

    处理GETPOST 请求并将数据传输到客户端等的servlet。

    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);
        }
    
    }
    

    我想这可以帮助你理解。

    【讨论】:

    • HTTP 状态 500 - java.lang.NullPointerException 消息 java.lang.NullPointerException 描述 服务器遇到一个内部错误,阻止它完成此请求。异常 org.apache.jasper.JasperException: java.lang.NullPointerException org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:549)
    • 你用过 Eclipse 之类的 IDE 吗?
    • @De De De De 清理您的服务器工作目录并重新启动服务器,重新运行您的应用程序。
    • 哇。感谢您花时间和精力写这篇文章。
    【解决方案2】:

    您的 JSP 页面工作正常,没有错误。检查您的数据库并确认您在 products 表中有行。因为方法getProductList() 没有返回ArrayList,所以发生空指针异常。

    【讨论】:

    • 我意识到我在 getProductList() 中的 ProductDataBean.java 中获得的连接为空。现在的问题是,如何进行更改以插入值?如果我将整个连接放在 getProductList() 中,则会出现错误消息
    • 类似“找不到合适的驱动程序”
    猜你喜欢
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-17
    • 1970-01-01
    • 2020-09-26
    • 1970-01-01
    相关资源
    最近更新 更多