1

I am trying to put attributes to session from my action class

public String execute()  {
    String result = Action.SUCCESS;

    if (username.equals("pavan") && password.equals("kumar")){
        System.out.println("Success");
        Map<String, Object> session = new HashMap<String, Object>();
        session.put("username", username);
        session.put("role", 1);
        ActionContext.getContext().setSession(session);
        return Action.SUCCESS;
    }
    else{
        System.out.println("Input");
        return Action.INPUT;    

    }
}

Success will be returned when username and password are valid and goes to appropriate JSP. but session attributes i did set are not visible in jsp

<% if(session == null || session.getAttribute("username") == null) {
System.out.println("No valid session found");
response.sendRedirect("/Test/index.jsp");
}%>

Above code is the jsp will redirect to index.jsp and "No valid session found" will be printed in console.

What am i missing?

Roman C
  • 49,761
  • 33
  • 66
  • 176
Pavan Kumar
  • 462
  • 5
  • 13

1 Answers1

0

You are missing the session is a different object in both cases. You don't need to use scriptlets in the code. If you want to put something to the session you should get the session map from the action context

Map<String, Object> session = ActionContext.getContext().getSession();
session.put("username", username);
session.put("role", 1);
return Action.SUCCESS;

or use servlet session directly

HttpSession session = ServletActionContext.getRequest().getSession(); 
session.setAttribute("username", username);
session.setAttribute("role", 1);
return Action.SUCCESS;

But the first case is preferable, due to it's supported by the framework.

Roman C
  • 49,761
  • 33
  • 66
  • 176
  • I am using SessionAware and it is working fine and before that i used your first solution and it was fine. But can you please elaborate actionContext.setSession() did not work. – Pavan Kumar Sep 11 '14 at 05:22
  • When you redirect a new action context is created by dispatcher and it sets a new session map. A `HashMap` has not a session scope for the entries you put there. As an alternative a `SessionMap` can be used or implement a scope strategy like in [this](http://stackoverflow.com/a/17394920/573032) answer. – Roman C Sep 11 '14 at 08:28