如何在过滤器中检索 FacesContext [英] How do I retrieve the FacesContext within a Filter

查看:17
本文介绍了如何在过滤器中检索 FacesContext的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在过滤器中检索 FacesContext?

How do I retrieve the FacesContext within a Filter?

我遵循了以下关于如何在 Filter 中检索 FacesContext 的文章:

I followed following article on how to retrieve the FacesContext in a Filter:

http://ocpsoft.org/java/jsf-java/jsf-20-extension-development-accessing-facescontext-in-a-filter/

但问题是它不适用于 Flash 范围.抛出以下 NPE:

But the problem is that it is not working with Flash scope. Following NPE is thrown:

java.lang.NullPointerException
at com.sun.faces.context.flash.ELFlash.loggingGetPhaseMapForWriting(ELFlash.java:751)
at com.sun.faces.context.flash.ELFlash.getPhaseMapForWriting(ELFlash.java:785)
at com.sun.faces.context.flash.ELFlash.put(ELFlash.java:392)
at com.sun.faces.context.flash.ELFlash.put(ELFlash.java:112)

我想在我的过滤器中添加重定向并使用 flash 作用域来保存一些数据和消息,但它不起作用.

I want to add redirection in my filter and use flash scope to save some data and also Messages, which is not working.

推荐答案

如何在过滤器中检索 FacesContext?

你不能.FacesContextFacesServlet 创建,因此仅在由 FacesServlet 处理的任何 Java 代码中可用,它涵盖所有 JSF 工件,例如作为托管 bean 和阶段侦听器.文章只展示了如何手动创建FacesContext,但这种方法最终是没有用的.FacesContext 只是标准 Servlet API 已经可用的所有内容的抽象,例如 HttpServletRequestHttpSessionServletContext,等等.直接使用它们,就像 JSF 在幕后"所做的一样.

You cannot. The FacesContext is created by the FacesServlet and thus only available within any Java code which is processed by the FacesServlet, which covers all JSF artifacts, such as managed beans and phase listeners. The article only shows how to manually create the FacesContext, but this approach is ultimately useless. The FacesContext is just an abstraction of everything already available by standard Servlet API such as HttpServletRequest, HttpSession, ServletContext, etc. Just use them directly the same way as JSF is doing "under the hoods".

您有两个选择:

  1. 改用 JSF PhaseListener.根据您没有提及的具体功能需求,这可能是一个相当笨拙的解决方案/解决方法.

  1. Use a JSF PhaseListener instead. Depending on the concrete functional requirement which you didn't tell anything about, this may be a rather clumsy solution/workaround.

不要使用 JSF 提供的 Flash 作用域工具,而是自己自制一个.原理很简单:在初始请求上设置一个 cookie,发送一个重定向,在重定向的请求中查找 cookie 删除它(以便它在任何后续请求中不再存在).这正是 JSF Flash 作用域在幕后工作的方式.另请参阅 将通知消息设置为请求属性应该在 sendRedirect 之后显示 一个具体的例子.

Don't use JSF-provided Flash scope facility, but homebrew one yourself. The principle is rather simple: set a cookie on initial request, send a redirect, in the redirected request lookup the cookie and remove it (so that it's not there anymore on any subsequent request). That's exactly how the JSF Flash scope works under the hoods. See also Set notification message as request attribute which should show after sendRedirect for a concrete example.

这篇关于如何在过滤器中检索 FacesContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆