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 s
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.
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 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);
}
Try and check of your ServletResponse response is an instanceof HttpServletResponse like so:
if (response instanceof HttpServletResponse) {
response.sendRedirect(....);
}