Can a Servlet send to two different JSP?

Asked

Viewed 588 times

2

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

In my Serrvlet I use:

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

that sends to resposta.jsp.

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

2 answers

4


You don’t 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 some 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);

he’ll send to resposta2.jsp and the first created object will be disregarded.

  • You set the example you gave me. But I have a problem now. I have an IF and ELSE IF and the two send to the same page only with different values, but if the person enters the if option(shows the result) and the person goes back to the page and tries the Else if option, it doesn’t work. You know what I can do?

  • 1

    @Peaceful back on vacation now, since I take a look at it

  • 1

    @Peaceful man, I let your question fall into oblivion, rs.. It was bad. You already solved?

  • Yes. Anyway, thank you for your concern.

2

Since you’re doing a forward on a jsp and not on 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 Directive taglib with Uri.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.