Can a servlet send to two different JSPs?

2

My page index.jsp uses the Servlet and then sends it to resposta.jsp . In resposta.jsp depending on the button, I use the Servlet to use another Java function. But I do not know how to make this use.

In my servlet I use:

RequestDispatcher rd = request.getRequestDispatcher("resposta.jsp");
rd.forward(request,response);

which sends to resposta.jsp .

PS: remembering that I already use an if / elseif to check which one should be sent, my problem is not knowing if I can create two getRequest or something like this.

    
asked by anonymous 14.11.2014 / 01:36

2 answers

4

You do not need to create two RequestDispatcher objects, you can create the variable that stores the object reference first, and then you create the object within the if. Example:

RequestDispatcher rd;
if (/*condicao*/) {
    rd = request.getRequestDispatcher("resposta1.jsp");
}
else {
    rd = request.getRequestDispatcher("resposta2.jsp");         
}
rd.forward(request, response);

But if by chance you create two different objects, it will just leave the reference on the first side. Example:

RequestDispatcher rd;
rd = request.getRequestDispatcher("resposta1.jsp");
rd = request.getRequestDispatcher("resposta2.jsp");         
rd.forward(request, response);

it will send to resposta2.jsp and the first created object will be disregarded.

    
14.11.2014 / 11:02
2

As you are doing a forward in a jsp and not in the servlet, you can use jstl instead of pure java, like this:

<c:choose>
  <c:when test="${condicao}">
    <jsp:forward page="/url1.jsp" />
  </c:when>
  <c:otherwise>
    <jsp:forward page="/url2.jsp" />
  </c:otherwise>
</c:choose>

Remembering that you need to add the jstl library and the directive taglib with uri.

    
24.11.2014 / 19:51