我正在尝试从程序的会话中检索数据。我的问题是我想检查某些东西是否已经存在或刚刚创建。因此,我想像这样检查会话:
//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
.是否有可能解决这个问题?
好的,这里是解决方案。
这段代码以某种方式工作。我不知道为什么,但它有效,这就是我想要的一切: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 是否为空
博士
OP equals()
改为==
,所以i
null
你是巨魔吧?: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();
}
}