Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 243
wasimbhalli Avatar asked Mar 15 '11 07:03

wasimbhalli


People also ask

How do I redirect one servlet to another?

The sendRedirect() method of HttpServletResponse interface can be used to redirect response to another resource, it may be servlet, jsp or html file. It accepts relative as well as absolute URL. It works at client side because it uses the url bar of the browser to make another request.

What is the difference between doing a forward versus a sendRedirect in a servlet?

When we use the forward method request is transferred to other resources within the same server for further processing. In case of sendRedirect request is transferred to another resource to a different domain or different server for further processing.

How does filter work in servlet?

A filter is an object that is invoked at the preprocessing and postprocessing of a request. It is mainly used to perform filtering tasks such as conversion, logging, compression, encryption and decryption, input validation etc. The servlet filter is pluggable, i.e. its entry is defined in the web.


2 Answers

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.

like image 138
Dead Programmer Avatar answered Oct 03 '22 08:10

Dead Programmer


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

like image 41
jmj Avatar answered Oct 03 '22 10:10

jmj