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.
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.
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.
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.
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.
You should return
after redirecting:
response.sendRedirect("index.jsp");
return;
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With