How to redirect a servlet filter?

I am trying to find a method to redirect my request from a filter to a login page, but I do not know how to redirect from a servlet. I searched, but I find the sendRedirect() method. I cannot find this method when responding to a filter in filters. What reason? How can i solve this?

+42
java redirect servlets servlet-filters
Mar 15 '11 at 7:44
source share
5 answers

In the filter, the response is ServletResponse , not HttpServletResponse . Hand over the cast to the HttpServletResponse .

 HttpServletResponse httpResponse = (HttpServletResponse) response; httpResponse.sendRedirect("/login.jsp"); 

If the context path is used:

 httpResponse.sendRedirect(req.getContextPath() + "/login.jsp"); 

Also remember to call return; in the end.

+58
Mar 15 2018-11-11T00:
source share

I am trying to find a method to redirect my request from a filter to the login page

Not

You just call

 chain.doFilter(request, response); 

away from the filter and normal flow will go forward.

I don't know how to redirect from servlet

you can use

 response.sendRedirect(url); 

to redirect from servlet

+8
Mar 15 2018-11-11T00:
source share

If you also want to save the hash and get the parameter, you can do something like this (fill in redirectMap when initializing the filter):

 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); } 
+5
Sep 19 '13 at 2:34 on
source share

Try and check your ServletResponse response as instanceof HttpServletResponse like this:

 if (response instanceof HttpServletResponse) { response.sendRedirect(....); } 
+1
Mar 15 2018-11-11T00:
source share

Your response object is declared as ServletResponse . To use the sendRedirect() method, you must point it to HttpServletResponse . This is an advanced interface that adds methods related to the HTTP protocol.

0
Mar 15 2018-11-11T00:
source share



All Articles