检索表单会话而不保存

时间:2015-01-05 21:16:12

标签: jsf session

我正在尝试从我的程序的会话中检索数据。我的问题是我想检查是否已经存在或刚刚创建了什么。因此,我想检查这样的会话:

//status if party exists or not

FacesContext context = FacesContext.getCurrentInstance();  
HttpServletRequest request = (HttpServletRequest)context.getExternalContext().getRequest();  
HttpSession httpSession = request.getSession(false);  

String i = (String) httpSession.getAttribute("create");

//in case of the party doesn't exists
if (i.equals(null)) {
    httpSession.setAttribute("create", "1"); //I never used a set before for this value
    homeBean.getParty().setOrgKey(generateKey("org"));
    homeBean.getParty().setGastKey(generateKey("gast"));
    insertParty();          
}
else {
    updateParty();
}

我总是有NullPointerException。有可能解决这个问题吗?

1 个答案:

答案 0 :(得分:1)

好的就是溶剂。

此代码以某种方式工作。我不知道为什么但它有效,这就是我想要的一切:D

public void createParty() {
    // status ob die party existiert wird aus der session geholt
    FacesContext context = FacesContext.getCurrentInstance();
    HttpServletRequest request = (HttpServletRequest) context
            .getExternalContext().getRequest();
    HttpSession httpSession = request.getSession(false);

    if (httpSession.getAttribute("create") == null) {
        httpSession.setAttribute("create", 1);
        homeBean.getParty().setOrgKey(generateKey("org"));
        homeBean.getParty().setGastKey(generateKey("gast"));
        insertParty();
    } else {
        int i = (Integer) httpSession.getAttribute("create");
        if (i == 1) {
            updateParty();
        }
    }
}

就像有人说我应该检查httpSession是否为null

TL; DR

OP将equals()更改为==,因此inull

你是一个巨魔吗? :D几乎像每个软件开发者一样

好吧,但现在看起来像这样

//this method has to be called before createParty()
    public String cvParty() {
        party = new Party();
        FacesContext context = FacesContext.getCurrentInstance();
        HttpServletRequest request = (HttpServletRequest) context
                .getExternalContext().getRequest();
        HttpSession httpSession = request.getSession(false);
        httpSession.setAttribute("create", 0);
        return "partyDetail?faces-redirect=true&i=2";
    }

public void createParty() {
    // status ob die party existiert wird aus der session geholt
    FacesContext context = FacesContext.getCurrentInstance();
    HttpServletRequest request = (HttpServletRequest) context
            .getExternalContext().getRequest();
    HttpSession httpSession = request.getSession(false);

    if ((Integer) httpSession.getAttribute("create") == 1) {
        updateParty();
    }
    else {
        httpSession.setAttribute("create", 1);
        homeBean.getParty().setOrgKey(generateKey("org"));
        homeBean.getParty().setGastKey(generateKey("gast"));
        insertParty();
    }
}
相关问题