zhouwubai
zhouwubai

Reputation: 57

How to redirect servlet request to a html page in filter

I am writing a web app that redirect request (including html request and servlet request, $.post or $.get) a specific web page in a filter. it works for html page request. If I go to a web page I can not access, it redirects as expected. but If i click a button, send a servlet request that I can not access, it does not redirect. What it does is just return the content of web page REDIRECT_URL and the web page I clicked and sent request still there. Following is the code I am using to do redirection

 httpResponse.setContentType("text/html;charset=UTF-8");
            httpResponse.setHeader("pragma", "no-cache");
            httpResponse.setHeader("Cache-Control", "no-cache");

 httpRequest.getRequestDispatcher(REDIRECT_URL).forward(httpRequest, httpResponse);

How can I do what I expected in filter. I do not want to redirect in web. I want all work done by filter. Thanks..

Upvotes: 1

Views: 3538

Answers (1)

Brandon
Brandon

Reputation: 10028

getRequestDispatcher(REDIRECT_URL).forward does not redirect. It does a server-side forward, meaning the container will just make a different internal request behind the scenes.

What you want is HttpServletRequest.sendRedirect:

http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletResponse.html#sendRedirect(java.lang.String)

httpResponse.setContentType("text/html;charset=UTF-8");
httpResponse.setHeader("pragma", "no-cache");
httpResponse.setHeader("Cache-Control", "no-cache");

httpResponse.sendRedirect(REDIRECT_URL);

Upvotes: 2

Related Questions