获取会话地图

时间:2012-11-16 10:03:00

标签: jsf

在我的代码中,我有一个简单的Phase Listener

public class PhaseTracker implements PhaseListener {
    private static final Logger LOGGER = LoggerFactory.getLogger(PhaseTracker.class);

    @Override
    public void afterPhase(PhaseEvent pe) {
        LOGGER.debug("afterPhase " + pe.getPhaseId());
        LOGGER.debug(""+FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("haveErrors"));

    }

    @Override
    public void beforePhase(PhaseEvent pe) {
        LOGGER.debug("beforePhase " + pe.getPhaseId());
        boolean error = false;
        Iterator<FacesMessage> messageIterator = pe.getFacesContext().getMessages();
        while (messageIterator.hasNext()) {
            FacesMessage message = messageIterator.next();
            if (message.getSeverity().equals(FacesMessage.SEVERITY_ERROR)) {
                LOGGER.debug("beforePhase severity is error");
                error = true;
            }

        }

        FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("haveErrors", error);
        LOGGER.debug(""+FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("haveErrors"));
    }

    @Override
    public PhaseId getPhaseId() {
        LOGGER.debug("getPhaseId");
        return PhaseId.ANY_PHASE;
    }
}

问题是,当我尝试使用

访问变量时,在XHTML文件中
FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("haveErrors")

我有一个null来源,我不明白为什么。

1 个答案:

答案 0 :(得分:0)

试试这个

 public synchronized void beforePhase(PhaseEvent event) {

        FacesContext context = event.getFacesContext();
        ExternalContext ex = context.getExternalContext();

 String viewId = "/index.xhtml";

        if (context.getViewRoot() != null && context.getViewRoot().getViewId() != null) {
            viewId = context.getViewRoot().getViewId();

        }

        String localeCode = (String) ex.getSessionMap().get("localeCode");

        if (localeCode == null) {
            ex.getSessionMap().put("localeCode", "en");
            context.getViewRoot().setLocale(new Locale("en"));
            // System.out.println("locale code " +"En?");
        } else if (localeCode != null) {
            //System.out.println("locale code " +localeCode);
            ex.getSessionMap().put("localeCode", localeCode);
            context.getViewRoot().setLocale(new Locale(localeCode));
        }