简体   繁体   中英

How do I redirect to the current page in Servlet Filter?

I have a page say: /myapp/test.jsp?queryString=Y . The filter needs to redirect to current page. It should go to /myapp/test.jsp (without the query string). The below seems to bring it to to the context root: /myapp . I am running in WAS6.1.

public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpReq = (HttpServletRequest) req;
        HttpServletResponse httpResp = (HttpServletResponse) resp;
{
   boolean blnNeedToRedirect = true;
   if (blnNeedToRedirect) {
      httpResp.sendRedirect(".");
      return;
   }

   chain.doFilter(req, resp);
}

Use HttpServletrequest.getRequestURI . This should work for you:

httpResp.sendRedirect(httpReq.getRequestURI());

httpReq.getRequestURI() Gives you the servlet path and it should work as follows. In order to redirect to the same page, run the next command:

((HttpServletResponse) httpResp).sendRedirect(httpResp.encodeRedirectURL(httpReq.getRequestURI()));

Another Option is to add the Header Location with a status code 302 as follows:

((HttpServletResponse) httpResp).setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY); 
((HttpServletResponse) httpResp).addHeader("Location", request.getRequestURL().toString());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM