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?
This question is related to
java
servlets
redirect
servlet-filters
If you also want to keep hash and get parameter, you can do something like this (fill redirectMap at filter init):
String uri = request.getRequestURI();
String[] uriParts = uri.split("[#?]");
String path = uriParts[0];
String rest = uri.substring(uriParts[0].length());
if(redirectMap.containsKey(path)) {
response.sendRedirect(redirectMap.get(path) + rest);
} else {
chain.doFilter(request, response);
}
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
Your response object is declared as a ServletResponse
. To use the sendRedirect()
method, you have to cast it to HttpServletResponse
. This is an extended interface that adds methods related to the HTTP protocol.
Try and check of your ServletResponse response
is an instanceof HttpServletResponse
like so:
if (response instanceof HttpServletResponse) {
response.sendRedirect(....);
}
Source: Stackoverflow.com