4

我的项目正在使用 JSF2.0 和 CDI。对于一页,我希望我的支持 bean 与页面的生命周期相匹配。@ViewScoped 似乎非常合适,但它不是 CDI 的一部分,然后使我们的解决方案不一致。那么我的下一个选择是 CDI @ConversationScoped。在我看来,标记对话边界的唯一方法是通过 conversation.begin 和 conversation.end 的程序方式(我使用过 Seam 2.x,在那里你可以使用注释来标记对话边界)。我的页面位于具有全局导航的通用布局中,这意味着有“无限”的方式可以离开我的页面。无论用户选择哪种方式,我如何确保对话结束(例如,单击一个完全不在我的支持 bean 控制范围内的全局导航选项)?我希望该解决方案不会将代码传播到其他模块;

4

2 回答 2

4

这可以通过自定义来实现ConfigurableNavigationHandler

  1. 实现一个 JSF NavigationHandler

     public class NavigationHandlerTest extends ConfigurableNavigationHandler {
    
     private NavigationHandlerTest concreteHandler;
    
     public NavigationHandlerTest(NavigationHandler concreteHandler) {
          this.concreteHandler = concreteHandler;
     }
    
    
     @Override
     public void handleNavigation(FacesContext context, String fromAction, String outcome) 
     {
        //here, check where navigation is coming from and based on that, retrieve the CDI bean and kill the conversation
         if(fromAction.equals("someAction"){
         BeanManager theBeanManager = getBeanManager(context);
         Bean bean = theBeanManager.getBeans("yourCDIBean").iterator().next() 
         CreationalContext ctx = theBeanManager.createCreationalContext(bean);
         MyBeanType o = theBeanManager.getReference(bean, bean.getClass(), ctx); //retrieve the bean from the manager by name. You're guaranteed to retrieve only one of the same name;
         o.getConversation.end(); //end the conversation from the bean reference
          }
    
         //proceed with normal navigation
         concreteHandler.handleNavigation(context, fromAction, outcome);   
    
     }
    
     //This method provides access to the cdi bean manager. You need it to be able to 
     //gain access to the cdi bean and from that to the injected conversation instance
     public BeanManager getBeanManager(FacesContext facesContext){
       BeanManager cdiBeanManager = (BeanManager)((ServletContext) facesContext.getExternalContext().getContext()).getAttribute("javax.enterprise.inject.spi.BeanManager"); 
        return cdiBeanManager;
     }
    
    
       } 
    
  2. 在faces-config.xml中注册您的自定义导航处理程序

     <application>
         <navigation-handler>com.foo.bar.NavigationHandlerTest</navigation-handler>
     </application>
    

这种方法是集中的和微创的

于 2013-03-15T20:44:14.950 回答
0

据我所知 - 你不能。在 JSF 中,几乎不可能(很难)确定链接是在当前选项卡还是新选项卡中打开(对于新选项卡,您需要保持对话处于活动状态)。

但好消息 - 闲置 10 分钟后(默认情况下),对话将自动关闭。

于 2013-03-13T21:46:50.770 回答