How to redirect in a servlet filter?

wasimbhalli picture wasimbhalli · Mar 15, 2011 · Viewed 106.4k times · Source

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?

Answer

Dead Programmer picture Dead Programmer · Mar 15, 2011

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.