空指针异常(在 Struts2 上执行会话)

Null pointer exception (implementing session on Struts2)

我遵循了很多关于如何在 Struts 2 项目中使用 SessionAware 的示例,当我想将数据放入会话中时,我总是得到 NullPointerException。为什么?

public class UserService extends ActionSupport implements SessionAware {

private Map<String,Object> sessionmap;

@Override  
public void setSession(Map<String, Object> sessionmap) {  
    this.sessionmap = sessionmap;
}

public String execute() {
    sessionmap.put("id", iduser);
    return SUCCESS;
}

正如 Wesley 所说,问题是会话映射为空,这就是为什么你得到空指针 eception,解决方案是在 execute 方法中的 put 之前添加这个 this.sessionmap = ActionContext.getContext().getSession(); 像这样

public String execute(){
        this.sessionmap = ActionContext.getContext().getSession();
        sessionmap.put("id", iduser);
    return SUCCESS;
}