---
title: "JSF的PhaseListener的扩展"
author: "hongsoft"
date: "2008-03-10T20:21:00Z"
tags: []
slug: "jsf-phaselistener"
draft: false
lastmod: "2008-03-10T20:21:00Z"
id: 287384
url: "https://hongsoft.iteye.com/blog/287384"
---

最近做 JSF和我们自己实现的 pageFlow的整合，基本已经完全调通了。过程中间考虑到了对JSF的 PhaseListener的扩展，后来发现这个思路对我们这个工作并没有帮助，但是 已经摸透了这个技术点，就记录下来，以后可以查查看。

1)faces-config.xml的编辑  
 &lt;lifecycle&gt;  
            &lt;phase-listener&gt;com.primeton.jsf.FlowPhaseListener&lt;/phase-listener&gt;  
&lt;/lifecycle&gt;  
就可以了。

2)listener的编辑  
因为马上就要从 自己的代码中把这个多余的代码去掉，所以，还是把code全部copy出来吧。

public class FlowPhaseListener implements PhaseListener {

    public void afterPhase(PhaseEvent event) {  
        // TODO Auto-generated method stub           
    }

    public void beforePhase(PhaseEvent event) {  
        FacesContext context=event.getFacesContext();  
        HttpServletRequest request=(HttpServletRequest)( context.getExternalContext().getRequest());         
        UIViewRoot root=context.getViewRoot();         
        String theActionString=getActionString(root);  
        if(theActionString==null)  
            return ;  
        else  
        {//下面是我们想在listener中做的事情  
            int i=theActionString.indexOf(".flow");  
            request.setAttribute("\_eosFlowID", theActionString.substring(0, i+5));  
            request.setAttribute("\_eosFlowAction", theActionString.substring(i+6,theActionString.length()));  
        }

    }  
    //访问组件树哦，这个功能不错  
    private String getActionString(UIComponent comp)  
    {     
        String theActionString=null;  
        for (Iterator it = comp.getFacetsAndChildren(); it.hasNext(); )  
        {  
            UIComponent childOrFacet = (UIComponent)it.next();             
            if(childOrFacet instanceof ActionSource)  
            {  
                ActionSource source = (ActionSource) childOrFacet;                 
                theActionString=source.getAction().toString();  
                if(null!=theActionString&&theActionString.length()&gt;0&&theActionString.indexOf(".flow")&gt;0)  
                    return theActionString;  
            }  
            theActionString=getActionString(childOrFacet);  
        }  
        return theActionString;  
    }  
   //指定某个阶段  
    public PhaseId getPhaseId() {  
        // TODO Auto-generated method stub  
        return PhaseId.PROCESS\_VALIDATIONS;  
    }

PhaseListener的思路和在JSF中的地位大家应该都已经清楚的，否则应该也不会看这个文章，这里就不说了。