wasimbhalli
wasimbhalli

Reputation: 5242

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?

Upvotes: 59

Views: 128021

Answers (6)

deepak lodhi
deepak lodhi

Reputation: 51

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

Upvotes: 3

Dead Programmer
Dead Programmer

Reputation: 12585

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.

Upvotes: 87

user1079877
user1079877

Reputation: 9398

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);
}

Upvotes: 10

jan.vdbergh
jan.vdbergh

Reputation: 2119

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.

Upvotes: 1

Buhake Sindi
Buhake Sindi

Reputation: 89189

Try and check of your ServletResponse response is an instanceof HttpServletResponse like so:

if (response instanceof HttpServletResponse) {
    response.sendRedirect(....);
}

Upvotes: 2

Jigar Joshi
Jigar Joshi

Reputation: 240956

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

Upvotes: 13

Related Questions