0

I need to store the username variable into session.

Map<String, Object> sessionname; 
String uname="SomeValue";
    public void setSession(Map map) {

    sessionname=ActionContext.getContext().getSession();
    sessionname.put("uname", username);//inserting String to the session variable

}

On another action page if I get this value back to a string then it shows null. Instead of giving string if I give string in double quotes it is getting on the action page.

String l=(String)session.getAttribute("uname"); 
System.out.println(l); //gives the value as null

If it is not possible give me another solution to pass a particular variable to other pages. I am developing an image sharing application using struts. In order to upload the image I need to pass the name of the user to the action page corresponding to the image uploading process.

Andrea Ligios
  • 49,480
  • 26
  • 114
  • 243

1 Answers1

0

Do not reinvent the wheel.

Struts2 already uses a SessionMap wrapper object, among the others.

Simply implements SessionAware interface, and provide a setter for your object; then put and retrieve your object from that map, that will be automatically handled by all your actions implementing SessionAware interface:

public class FirstAction implements SessionAware {

    private Map<String,Object> session;
    public void setSession(Map<String,Object> session){ 
        this.session = session;
    }

    private String username; /* with Getter and Setter */

    public String execute(){
        session.put("uname", username);
        return SUCCESS;
    }
}

public class SecondAction implements SessionAware {

    private Map<String,Object> session;
    public void setSession(Map<String,Object> session){ 
        this.session = session;
    }

    public String execute(){
        System.out.println(session.get("uname"));
        return SUCCESS;
    }
}

That said, it would be better to implement SessionAware only from a parent Action, to avoid redundancy, and to extend that Action from all the actions that need to access the Session Map.

Community
  • 1
  • 1
Andrea Ligios
  • 49,480
  • 26
  • 114
  • 243