I was learning how to do this myself, and this discussion was helpful. This, combined from material from various webpages and the book "Struts 2 in Action" got me to where I needed to be.
Nate's and nacho4d's answers are close to the mark. Here is what I did:
Required imports:
import java.util.Map;
import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts2.interceptor.SessionAware;
My action class ("User") declaration:
public class User extends ActionSupport implements SessionAware {
My session variable is a data member of User:
Map <String, Object> session;
Then, in my method that authenticates the user (note that UserModel is simple class of just data members and their getter/setters)
UserModel user;
...
session.put("User", user);
Finally, in my jsp file:
<s:if test="%{#session.User.isLoggedIn()}">
Welcome back, <s:property value="%{#session.User.firstName}" />
<s:property value="%{#session.User.middleName}" />
<s:property value="%{#session.User.lastName}" />!
<a href="Logout.action">Logout</a>
</s:if>
Notice the syntax of accessing the session objects methods/data members. Although I've not read it detailed somewhere, I'm guessing that:
- %{} tells jsp to evaluate the expression inside the {}
- #session gets you access to the session stack/object?
And from there, the result is normal dot operators for accessing objects and their methods/members.
I'm a novice at this, but it also seems like it doesn't matter if the UserModel's data members are private, the JSP can access them anyway.
Oh. One last bit, to make it "complete", how about logging out? My java for the logout action:
public String logoutUser()
{
session.remove("User");
return SUCCESS;
}