Я не могу перенести данные из MySQL в Jsp - PullRequest
0 голосов
/ 01 мая 2018

Я пытаюсь перенести данные из Mysql в Jsp (используя Tomcat Server), но я не могу получить данные, и мой код не показывает ошибок. Когда я запускаю его как приложение Java, я вижу данные mysql с моего контроллера. Я буду рад, если вы сможете помочь в этом вопросе.

Вы можете посмотреть мою базу данных здесь https://ibb.co/iauGYn

Модель класса

public class Book{
protected int id;
protected String title;
protected String author;
protected float price;

public Book() {
}

public Book(int id) {
    this.id = id;
}

public Book(int id, String title, String author, float price) {
    this(title, author, price);
    this.id = id;
}

public Book(String title, String author, float price) {
    this.title = title;
    this.author = author;
    this.price = price;
}

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public String getTitle() {
    return title;
}

public void setTitle(String title) {
    this.title = title;
}

public String getAuthor() {
    return author;
}

public void setAuthor(String author) {
    this.author = author;
}

public float getPrice() {
    return price;
}

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

Просмотр Jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
    <title>Books Store Application</title>
</head>
<body>
    <div align="center">
        <table border="1" cellpadding="5">
            <caption><h2>List of Books</h2></caption>
            <tr>
                <th>ID</th>
                <th>Title</th>
                <th>Author</th>
                <th>Price</th>
                <th>Actions</th>
            </tr>
            <c:forEach var="book" items="${listBook}">
                <tr>
                    <td><c:out value="${book.id}" /></td>
                    <td><c:out value="${book.title}" /></td>
                    <td><c:out value="${book.author}" /></td>
                    <td><c:out value="${book.price}" /></td>
                    <td>

                        <a href="/edit?id=<c:out value='${book.id}' />">Edit</a>
                        &nbsp;&nbsp;&nbsp;&nbsp;
                        <a href="/delete?id=<c:out value='${book.id}' />">Delete</a>                     
                    </td>
                </tr>
            </c:forEach>
        </table>
    </div>   
</body>
</html>

Класс BookDAO для операций с БД

public class BookDAO {
private String jdbcURL;
private String jdbcUsername;
private String jdbcPassword;
private Connection jdbcConnection;

public BookDAO(String jdbcURL, String jdbcUsername, String jdbcPassword) {
    this.jdbcURL = jdbcURL;
    this.jdbcUsername = jdbcUsername;
    this.jdbcPassword = jdbcPassword;
}

protected void connect() throws SQLException {
    if (jdbcConnection == null || jdbcConnection.isClosed()) {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            throw new SQLException(e);
        }
        jdbcConnection = DriverManager.getConnection(
                                    jdbcURL, jdbcUsername, jdbcPassword);
    }
}

protected void disconnect() throws SQLException {
    if (jdbcConnection != null && !jdbcConnection.isClosed()) {
        jdbcConnection.close();
    }
}

public List<Book> listAllBooks() throws SQLException {
    List<Book> listBook = new ArrayList<>();

    String sql = "SELECT * FROM book";

    connect();

    Statement statement = jdbcConnection.createStatement();
    ResultSet resultSet = statement.executeQuery(sql);
    while (resultSet.next()) {
        int id = resultSet.getInt("id");
        String title = resultSet.getString("title");
        String author = resultSet.getString("author");
        float price = resultSet.getFloat("price");

        Book book = new Book(id, title, author, price);
        listBook.add(book);
    }

    resultSet.close();
    statement.close();

    disconnect();
    return listBook;
}

public Book getBook(int id) throws SQLException {
    Book book = null;
    String sql = "SELECT * FROM book WHERE id = ?";

    connect();

    PreparedStatement statement = jdbcConnection.prepareStatement(sql);
    statement.setInt(1, id);

    ResultSet resultSet = statement.executeQuery();

    if (resultSet.next()) {
        String title = resultSet.getString("title");
        String author = resultSet.getString("author");
        float price = resultSet.getFloat("price");

        book = new Book(id, title, author, price);
    }

    resultSet.close();
    statement.close();

    return book;
}

Класс контроллера.

public class BookController extends HttpServlet {
private static final long serialVersionUID = 1L;
private BookDAO bookDAO;

public void init() {

    String jdbcURL = getServletContext().getInitParameter("jdbc:mysql://localhost:3306/bookstore");
    String jdbcUsername = getServletContext().getInitParameter("root");
    String jdbcPassword = getServletContext().getInitParameter("root");

    bookDAO = new BookDAO(jdbcURL, jdbcUsername, jdbcPassword);

}

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    doGet(request, response);
}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String action = request.getServletPath();

    listBook(request, response);
}

private void listBook(HttpServletRequest request, HttpServletResponse response)
{

    List<Book> listBook = null;
    try {
        listBook = bookDAO.listAllBooks();
    } catch (SQLException e) {
        e.printStackTrace();
    }
    request.setAttribute("listBook", listBook);
    RequestDispatcher dispatcher = request.getRequestDispatcher("BookList.jsp");
    try {
        dispatcher.forward(request, response);
    } catch (ServletException | IOException e) {
        e.printStackTrace();
    }
}

private void showNewForm(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    RequestDispatcher dispatcher = request.getRequestDispatcher("BookForm.jsp");
    dispatcher.forward(request, response);
}

private void showEditForm(HttpServletRequest request, HttpServletResponse response)
        throws SQLException, ServletException, IOException {
    int id = Integer.parseInt(request.getParameter("id"));
    Book existingBook = bookDAO.getBook(id);
    RequestDispatcher dispatcher = request.getRequestDispatcher("BookForm.jsp");
    request.setAttribute("book", existingBook);
    dispatcher.forward(request, response);

}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...