0

I am new to Struts2 and I am trying to retrieve an attribute I set in the action class.

LoginAction.java:

public class LoginAction extends ActionSupport implements SessionAware {
    private static final long serialVersionUID = 1L;

    private Map<String, Object> session;

    // field variables

    @Override
    public String execute() {
        UserManager um = new UserManager();
        String registeredPassword = um.getCurrentUserDetail("user_password", getUserId());

        if(getUserPassword().equals(registeredPassword)) {
            String currentUserId = um.getCurrentUserDetail("user_id", userId);
            int currentUserType = um.getCurrentUserType(userId);

            session.put("currentUserId", (String) currentUserId);
            session.put("currentUserType", (Integer) currentUserType);

            System.out.println("You have successfully logged in!");
            return SUCCESS;
        }

        System.out.println("Your login has failed!");
        return ERROR;
    }

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

    // getters and setters
}

struts.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
    "http://struts.apache.org/dtds/struts-2.3.dtd">

<struts>
    <package name="default" extends="struts-default">
        <action name="login" class="com.mypackage.model.LoginAction">
            <result name="success">/index.jsp</result>
            <result name="error">/login.jsp</result>
        </action>
    </package>
</struts>

index.jsp:

<%@ taglib prefix="s" uri="/struts-tags"%>
<%@ page import="com.mypackage.model.LoginAction" %>

<head>    
<%
    int type = 0;

    if(session.containsKey("currentUserType")) {
        type = (Integer) session.get("currentUserType");
    }
%>
</head>

However, the methods containsKey() and get() are returning undefined for session. How do I get the attributes that was put in session in Struts2?

k_rollo
  • 5,304
  • 16
  • 63
  • 95

1 Answers1

2

It's happening because from Scriptlet you are reading the HttpSession, not the wrapping Struts2 SessionMap. You can read more info here.

But do yourself a favor and avoid using scriptlet completely, forever. And ever.

Assuming you really need to assign a value to a variable (it could probably be avoided too, but let's go small steps first), do it the Struts way:

<s:set var="type" value="0" />
<s:if test='#session.containsKey("currentUserType")'>
    <s:set var="type" value='#session["currentUserType"]' />
</s:if>

Or one-liner

<s:set var="type" 
     value='%{#session["currentUserType"]!=null?#session["currentUserType"]:0}'

Or much better, in Action class:

public Integer getType(){
    return session.containsKey("currentUserType") 
                   ? session.get("currentUserType") 
                   : 0;
}

EDIT

I know (knew) what you are trying to achieve. I'm just telling you that there are several better alternatives. Does that JSP seem clean to you ?

For example if you have three main profiles, you can create three JSP snippets for your header, and with <s:if type="... include only the right one (with <jsp:include>, or better <s:include>, NOT with <%@ include %>).

Consider having a main-head.jsp included in all of your JSPs;

in main-head.jsp:

<s:if test="type==0">
    <s:include page="guest-head.jsp"/>
</s:if>
<s:elseif test="type==1">
    <s:include page="admin-head.jsp"/>
</s:elseif>
<s:elseif test="type==2">
    <s:include page="user-head.jsp"/>
</s:elseif>

Still ugly (this is a start), but much better.

The first part of the answer is still completely valid, but keep in mind this new part too, to improve the design of your pages.

Community
  • 1
  • 1
Andrea Ligios
  • 49,480
  • 26
  • 114
  • 243
  • Hi there, certain parts of the `index.jsp` turn on/off depending on the `type` (0 = guest, 1 = admin, 2 = user). Different user types see different things on the same jsp, so that is why I need to get the `type` in the jsp. Let me post the whole `index.jsp` to show what I was trying to achieve. If you can elaborate on the Action class approach after seeing the whole code, it would be much appreciated. Thanks. – k_rollo Nov 13 '14 at 16:35
  • 1
    I have a follow-up question but it's regarding the Struts2 if-else-if. However, I think it may need it's own thread as it may deviate from this topic. Thanks for your response. – k_rollo Nov 14 '14 at 02:26