java 如何重定向到 Servlet 过滤器中的当前页面?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1531197/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 16:57:42  来源:igfitidea点击:

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

javaredirectservlet-filters

提问by JeffJak

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.

我有一个页面说: /myapp/test.jsp?queryString=Y。过滤器需要重定向到当前页面。它应该转到/myapp/test.jsp(没有查询字符串)。下面似乎将它带到上下文根: /myapp。我在 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);
}

回答by skaffman

Use HttpServletrequest.getRequestURI. This should work for you:

使用HttpServletrequest.getRequestURI。这应该适合你:

httpResp.sendRedirect(httpReq.getRequestURI());

回答by Hesham Yassin

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:

httpReq.getRequestURI() 为您提供 servlet 路径,它应该按如下方式工作。为了重定向到同一页面,运行下一个命令:

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

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

另一种选择是添加Location状态码为 302的 Header ,如下所示:

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