B
B
Boris_ANTIHYPE2018-11-13 12:30:15
Java
Boris_ANTIHYPE, 2018-11-13 12:30:15

How to display information from the database in JSP?

It is necessary to transfer the list to the jsp page to the table! Everything is output to the console, but the jsp page is empty
servlet

public class CatController extends HttpServlet {

    private Connection connection = null;
    private Util util = new Util();

    private static final String SQL_GET_ALL_CAT = "SELECT * FROM cat";

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        Statement statement = null;
        ResultSet resultSet = null;

        List<Cat> cats = new ArrayList<Cat>();

        try {
            connection = util.getConnection();
            connection.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
            connection.setAutoCommit(false);
            statement = connection.createStatement();

            ResultSet result = statement.executeQuery(SQL_GET_ALL_CAT);

            while (result.next()){
                Cat cat = new Cat();
                cat.setId(result.getInt("id"));
                cat.setName(result.getString("name"));
                cat.setAge(result.getInt("age"));
                cat.setColor(result.getString("color"));
                cat.setGender(result.getString("gender"));
                cat.setBreed(result.getString("breed"));
                cat.setDad_id(result.getInt("dad_id"));
                cat.setMam_id(result.getInt("mam_id"));

                cats.add(cat);
            }

            req.setAttribute("cat", cats);
            req.getRequestDispatcher("index.jsp").forward(req, resp);

        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            try {
                if (resultSet != null)
                    resultSet.close();
                if (statement != null)
                    statement.close();
                if (connection != null)
                    connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

    }
}

jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

<table>
    <tr>
        <c:forEach var="cats" items="${cat}">
            <td>${cats.id}</td>
            <td>${cats.name}</td>
            <td>${cats.age}</td>
            <td>${cats.color}</td>
            <td>${cats.gender}</td>
            <td>${cats.breed}</td>
            <td>${cats.dad_id}</td>
            <td>${cats.mam_id}</td>
        </c:forEach>
    </tr>
</table>

</body>
</html>

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question