2010-08-05 94 views
13

我需要转发我的请求(对于jsp,但我认为这不重要)从一个http.Filter 如果原始请求的URI通过一些验证,我的过滤器运行。转发请求从一个过滤器

我发现这个page that faced similar task

我仍然需要计算如下:

  1. 我怎样才能获得的ServletContext在doFilter()方法(以呼叫转移API)getServletContext()不recignized

  2. 在转发之前还是转发之前,我还必须call chain.doFilter()? 另外,如果我的验证通过了,或者只有在验证失败的情况下(因为在这种情况下我不会继续转发我的页面),我还必须拨打chain.doFilter()吗?

这个问题实际上是继续this thread, 更加明显,代码可能是这样的:

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { 
     if (request instanceof HttpServletRequest) { 
      HttpServletRequest httpServletRequest = ((HttpServletRequest)request); 
      String requestURI = httpServletRequest.getRequestURI(); 
      String contextPath = httpServletRequest.getContextPath(); 
      if (<this is my implementation of the validation of this filter>){          
       getServletContext().getRequestDispatcher(
       "MySpecific.jsp").forward(request,response); 

      } 

     } 
     chain.doFilter(request,response); 

    } 

回答

10

如何我的doFilter得到的ServletContext()方法?

httpServletRequest.getSession().getServletContext(); 

我必须前进之前调用chain.doFilter(),之后向前或不呢?另外,如果我的验证通过了,或者只有在失败时才需要调用chain.doFilter()(因为在这种情况下,我不会继续转发我的页面)?

我会说,如果您转发请求,则不应该调用chain.doFilter() - 转发的请求将根据其自己的过滤器配置进行过滤。如果您的验证失败,则取决于您的Web应用的语义 - 如果原始页面是某种常规错误/登录/欢迎屏幕,则可能需要在验证失败时继续执行此操作。如果不了解更多情况,很难说。

10

要获得ServletContext,你有2个选择:在初始化过程中

  • 商店关闭FilterConfig和呼叫FilterConfig.getServletContext()

  • 呼叫HttpServletRequest.getSession().getServletContext()

我不t认为你一定需要ServletContext才能得到RequestDispatcher因为您可以拨打HttpServletRequest.getRequestDispatcher()

关于FilterChain.doFilter()打电话,如果您正在转发,我认为您不会打电话,因为一旦您转发,我假设您不希望发生任何标准行为。 如果你没有转发(你不会陷入你的if块),那么我会打电话给FilterChain.doFilter()方法,但是假设在另一端有一个目标被调用。

+0

这两个答案都很好。另一个是第一个。 – Spiderman 2010-08-09 07:01:32

+0

在初始化过程中关闭FilterConfig并调用FilterConfig.getServletContext()这是我首选的方法,因为没有明确的会话: – Gurnard 2012-11-07 13:36:10