Search code examples
javajspstruts2session-scope

Struts setSesssion() is not working


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?


Solution

  • 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.