0

I am having problem with redirect in jsp , the page just remains and doesn't throw any error.

I am able to do redirect when I direct write the script in my login.jsp like

<%
String redirectURL = "/client/index.jsp";
response.sendRedirect(redirectURL);
%>
<t:login title="Client Login">
..........
</t:login>

But I am unable to do redirect when I split the file into three and include it. below is my implementation.

login.jsp

<%@include file="/include/checkhandler.jsp"%>

checkhandler.jsp - this is a script that will check for file in handler folder and include it when it is exist.

......
request.getRequestDispatcher(handler).include(request, response);
......

login_handler.jsp this is the file the dispatcher will include

String redirectURL = "/client/index.jsp";
response.sendRedirect(redirectURL);
out.println("hello world");

After I execute this script , the hello world displayed but it is still stay at the same page without any error.

Leon Armstrong
  • 1,285
  • 3
  • 16
  • 41

2 Answers2

1

You need to use RequestDispatcher#forward() instead. Change your checkhandler.jsp to

request.getRequestDispatcher(handler).forward(request, response);

A server-side include is prohibited to change the response status code which is what happens when you use sendRedirect(). Any such attempt is simply ignored by the container.

From the RequestDispatcher#include() docs:

The ServletResponse object has its path elements and parameters remain unchanged from the caller's. The included servlet cannot change the response status code or set headers; any attempt to make a change is ignored.

This limitation is by design. The spec treats the web component being included as a guest i.e. it cannot direct the flow and any such attempts would be rightly ignored instead of throwing an exception to possibly allow an include for any servlet that you may have.

Only the hosting web component (the one doing an include) would be in complete control of the flow as well as what response headers are sent over to the client.

Ravi K Thapliyal
  • 51,095
  • 9
  • 76
  • 89
0

You have this in your code

out.println("hello world");
String redirectURL = "/client/index.jsp";
response.sendRedirect(redirectURL);

which will not work because you cannot redirect after writing to the response stream. The redirect is sent in the response header. The response body should not contain any html.

ramp
  • 1,256
  • 8
  • 14
  • the print is there to let op understand the execution run through that part , I corrected my question , thanks – Leon Armstrong Jan 20 '15 at 11:31
  • I think you are using the 'response' object in some way (somewhere in your 3 jsps). That is what is preventing your redirect. What remains is to figure out the who and how. – ramp Jan 20 '15 at 12:06