How to print session attributes in JSP with Struts 2

user3798114 picture user3798114 · Jul 16, 2014 · Viewed 9.5k times · Source

Here is what I have:

Java class (adding user):

public String addUser() throws NoSuchAlgorithmException {
    HttpSession currentSession = request.getSession();
    
    User u = new User();
    u.setUname(getUserName());
    u.setPassword(StringHash(getUserPass()));
    u.setUtype(getUserType());
    plResponse = iUserDAO.addUser(u);            
    setActionMessage(plResponse.getMessage());
    currentSession.setAttribute("actionMessage", this.actionMessage);

    return SUCCESS; 
}

Java class (adding associations):

public String saveAssoc() throws Exception {
    HttpSession currentSession = request.getSession();
   
    try {
        plResponse = iUserDAO.saveUserAssoc(currentSession.getAttribute("selectedUser").toString(), countryId, langId);
        
        refreshUserAssociations();            
        
        setActionMessage(plResponse.getMessage());
        currentSession.setAttribute("actionMessage", this.actionMessage);
    }
    catch (Exception e) {
        throw new Exception(e.getMessage());
    }
    return SUCCESS;
}

JSP (for both cases the same):

<s:if test="actionMessage != null && actionMessage != ''">
    <div class="successMessage">
    <br/><s:property value="actionMessage"/>
    </div>
    <br />
</s:if>

I have two cases of passing the return message to the page. After adding a user, and after adding user associations. In both cases the parameter is passed properly to session (I debuged the code), but it is being displayed only in the first case (adding user). The second case pretends like there is no actionMessage in session.

What may be the reason?

Answer

Roman C picture Roman C · Jul 16, 2014

Really neither first nor second case is displaying a message from session. It's looking a variable in the value stack.

In the first case you have the action property getter which returns a value. It could be not the same value in the second case.

The right way to use a session in action class is to implement SessionAware that injects via servletConfig interceptor a session map to the action bean property.

Then use that map instead of http session. See How do we get access to the session.

public String addUser() throws NoSuchAlgorithmException {    
    Map currentSession = ActionContext.getContext().getSession();
    User u = new User();
    u.setUname(getUserName());
    u.setPassword(StringHash(getUserPass()));
    u.setUtype(getUserType());
    plResponse = iUserDAO.addUser(u);
    setActionMessagee(plResponse.getMessage(currentSession.put("actionMessage",getActionMessagee()));
    return SUCCESS; 
}

In the JSP you can access the session object from the context.

<s:if test="#session.actionMessage != null && #session.actionMessage != ''">
    <div class="successMessage">
    <br/><s:property value="#session.actionMessage"/>
    </div>
    <br/>
</s:if>