Question

I have a servlet which can get requests by multiple JSP's.

But when I use the RequestDispatcher in the servlet, I don't know how to forward to the JSP that sent the request.

req.getRequestDispatcher("page.jsp").forward(req, resp);

I know there is something like this in html: javascript:javascript:history.go(-1)

I just need something like this:

req.setAttribute("originalRequest", req.getRequestPage());
req.getRequestDispatcher(originalRequest).forward(req, resp);

That piece of code is probably very noob but it gives you the idea of what I need.

So: I need to forward to the page that sent the original request (basically reload the page), but because multiple jsp's use the servlet, I cannot simply forward to "page.jsp"

Was it helpful?

Solution

You can do following

  • Create a hidden parameter for every jsp named jspName and give value for respective JSPs. e.g. for JSP A, parameter name is jspName and value is a, for JSP B, parameter name is jspName and value is b
  • Read this hidden parameter in the servlet using following code.

    String jspName = request.getParameter("jspName");
    RequestDispatcher rd = request.getRequestDispatcher(jspName);
    
    rd.forward(request, response);
    

When you are calling the servlet from JSP A, then it will have paramter japName=a, when servlet code is running, it will retrieve the value a from request.getParamter("jspName") and a getRequestDispatcher(jspName) will create the dispatcher for the same and rd.forward(request, response) will forward to the jsp.

OTHER TIPS

I have not tried the following, but I hope this may help you to solve your problem.

req.setAttribute("originalRequest", req.getRequestPage());
req.getRequestDispatcher(req.getAttribute(originalRequest).toString()).forward(req, resp);

I have tried in this way, It's working for me...

In JSP

You need to set this in every JSP. For ex: index.jsp is my jsp name.

<% session.setAttribute("jspName","index.jsp"); %>

In Servlet

request.getRequestDispatcher(session.getAttribute("jspName").toString()).forward(req, res);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top