Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot redirect with the response.sendRedirect

I googled and googled for hours on how to make a redirect in jsp or servlets. However when i try to apply it, it doesn't work.

Code that i have inside jsp page:

<%
    String articleId = request.getParameter("article_id").toString();
    if(!articleId.matches("^[0-9]+$"))
    {
       response.sendRedirect("index.jsp");
    }
%>

I know from debugging that regexp works and if any time, articleId is not number, the if goes inside, however when it reaches response.sendRedirect it doesn't actually makes redirect.

Do I miss something very fundamental in this case ?

Thanks in advance.

like image 998
Dmitris Avatar asked Jun 07 '09 03:06

Dmitris


People also ask

What is response sendRedirect?

sendRedirect() method redirects the response to another resource, inside or outside the server. It makes the client/browser to create a new request to get to the resource. It sends a temporary redirect response to the client using the specified redirect location URL.

Can not call sendRedirect after response committed?

The root cause of IllegalStateException exception is a java servlet is attempting to write to the output stream (response) after the response has been committed. It is always better to ensure that no content is added to the response after the forward or redirect is done to avoid IllegalStateException.

What's the difference between forward () include () and sendRedirect ()?

Difference between forward() and sendRedirect() methodThe forward() method works at server side. The sendRedirect() method works at client side. It sends the same request and response objects to another servlet. It always sends a new request.

What is difference between ServletResponse sendRedirect () and RequestDispatcher forward () method?

This is also called server side redirect. A RequestDispatcher forward() is used to forward the same request to another resource whereas ServletResponse sendRedirect() is a two step process. In sendRedirect(), web application returns the response to client with status code 302 (redirect) with URL to send the request.


2 Answers

You should return after redirecting:

response.sendRedirect("index.jsp");
return;
like image 81
objects Avatar answered Oct 03 '22 16:10

objects


Is there content before this scriptlet? If so, the redirect wouldn't work.

Also, the common practice is to have such logic inside a servlet or other class serving as controller, and leaving the JSP to only handle the rendering of the HTML. It may also solve your problem. For example, see here

like image 40
David Rabinowitz Avatar answered Oct 03 '22 14:10

David Rabinowitz