How to redirect in a servlet filter?
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?
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);
}
why are you using response object . it is a ServletResponse Object ,it does not provide sendRedirect() method . instead use request object of ServletRequest to forward the request.
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
// TODO Auto-generated method stub
// place your code here
request.getRequestDispatcher("login.html").forward(request,response);
return;
}
see javadoc
Try and check of your ServletResponse response
is an instanceof HttpServletResponse
like so:
if (response instanceof HttpServletResponse) {
response.sendRedirect(....);
}
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.
精彩评论