繁体   English   中英

Java MVC JSP从JavaBean获取连接和值

[英]Java MVC JSP get Connection and Values from JavaBean

我试图从JavaBean ProductDataBean.java中获取ShowProductCatalog.jsp中的值(列表productList = data.getProductList();)。 我收到错误nullpointerexception。 请帮忙! 您的帮助将不胜感激。

*编辑:我意识到在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;
    }
}

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

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

mysql-connector-java-5.1.24-bin.jar

你可以从这里得到

看看这样如何避免在jsp中的Java代码

我建议您使用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用户标准标签lib jstl1.2.jar呈现所有产品,您可以从此处获取它,因此将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。

产品.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);
    }

}

我认为这可以帮助您理解。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM