-2

I followed many examples on how to use SessionAware in a Struts 2 project and I always get a NullPointerException when I want to put data in the session. Why?

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;
}
Dave Newton
  • 152,765
  • 23
  • 240
  • 286

1 Answers1

-1

As Wesley said the problem is that session map is null thats why you get null pointer eception, the solution is to add this this.sessionmap = ActionContext.getContext().getSession(); before the put in the execute method like this

public String execute(){
        this.sessionmap = ActionContext.getContext().getSession();
        sessionmap.put("id", iduser);
    return SUCCESS;
}
  • 1
    No, this isn't the answer. This is *an* answer, but is almost always the wrong one--the reason `SessionAware` exists is to help S2 actions be as POJO-like as possible, which is an aid in testing. Reaching into `ActionContext` directly breaks that abstraction and makes testing (in particular) more difficult than necessary. – Dave Newton Mar 06 '20 at 21:19