在同一注册页面JSP和Servlet中加载数据列表

问题描述 投票:0回答:1

我在同一页面上有注册表格和表格,但是我的表格仅在我提交新注册时加载数据。打开页面时如何加载表格?我正在使用JSP和Servlet。我试图在问这里之前先进行搜索,但没有找到我需要的东西。

index.jsp

    <table class="table table-striped table-bordered">
        <thead class="thead-dark text-center">
            <tr>
                <th scope="col">CÓDIGO</th>
                <th scope="col">DATA</th>
                <th scope="col">QUANTIDADE</th>
                <th scope="col">VALOR</th>
                <th scope="col">VOLUME</th>
            </tr>
        </thead>

        <tbody>
            <c:forEach items="${investimentos}" var="inv">
                <tr>
                    <td><c:out value="${inv.codigo}"></c:out></td>
                    <td><c:out value="${inv.data}"></c:out></td>
                    <td><c:out value="${inv.quantidade}"></c:out></td>
                    <td>R$<c:out value="${inv.valor}"></c:out></td>
                    <td>R$<c:out value="${inv.valor * inv.quantidade}"></c:out></td>
                </tr>
            </c:forEach>
        </tbody>
    </table>

Servlet

@WebServlet("/registrarAcao")
public class Acao extends HttpServlet {
    private static final long serialVersionUID = 1L;

    private AcaoDAO acaoDAO = new AcaoDAO();

    public Acao() {
        super();
    }

    protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        try {
            RequestDispatcher view = req.getRequestDispatcher("/index.jsp");
            req.setAttribute("investimentos", acaoDAO.listar());
            view.forward(req, res);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        String codigo = req.getParameter("codigo");
        String dataString = req.getParameter("data");

        String quantidade = req.getParameter("quantidade");
        String valor = req.getParameter("valor");

        AcaoBean acao = new AcaoBean();
        acao.setCodigo(codigo);
        acao.setData(dataString);
        acao.setQuantidade(Double.parseDouble(quantidade));
        acao.setValor(Double.parseDouble(valor));
        acaoDAO.salvar(acao);

        try {
            RequestDispatcher view = req.getRequestDispatcher("/index.jsp");
            req.setAttribute("investimentos", acaoDAO.listar());
            view.forward(req, res);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
java jsp servlets
1个回答
0
投票

如果以/index.jsp开头,则无法查看表格。您需要以/registrarAcao开头,您将进入doGet方法,并且您的表格将被加载

© www.soinside.com 2019 - 2024. All rights reserved.