Issue
I have a registration form and table in the same page but my table only load data when i submit a new registration. How can i load the table when i open the page? Im using JSP and Servlet. I tried to search before asking here but i didnt find what i need.
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();
}
}
}
Solution
You cant view the table if you start with /index.jsp
. You need to start with /registrarAcao
and you will get to doGet
method and you table will be loaded
Change welcome page
<welcome-file-list>
<welcome-file>index.page</welcome-file>
</welcome-file-list>
Answered By - vadtel