I'm trying to find a method to redirect my request from a filter to the login page but I don't know how to redirect from servlet. I've searched but what I find is sendRedirect()
method. I can't find this method on my response object in the filter. What's the cause? How can I solve this?
The sendRedirect() method of HttpServletResponse interface can be used to redirect response to another resource, it may be servlet, jsp or html file. It accepts relative as well as absolute URL. It works at client side because it uses the url bar of the browser to make another request.
When we use the forward method request is transferred to other resources within the same server for further processing. In case of sendRedirect request is transferred to another resource to a different domain or different server for further processing.
A filter is an object that is invoked at the preprocessing and postprocessing of a request. It is mainly used to perform filtering tasks such as conversion, logging, compression, encryption and decryption, input validation etc. The servlet filter is pluggable, i.e. its entry is defined in the web.
In Filter the response is of ServletResponse
rather than HttpServletResponse
. Hence do the cast to HttpServletResponse
.
HttpServletResponse httpResponse = (HttpServletResponse) response; httpResponse.sendRedirect("/login.jsp");
If using a context path:
httpResponse.sendRedirect(req.getContextPath() + "/login.jsp");
Also don't forget to call return;
at the end.
I'm trying to find a method to redirect my request from filter to login page
Don't
You just invoke
chain.doFilter(request, response);
from filter and the normal flow will go ahead.
I don't know how to redirect from servlet
You can use
response.sendRedirect(url);
to redirect from servlet
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