SessionAware Interface Example
The SessionAware interface must be implemented by the Action class to store the information in the session scope.
Method of SessionAware interface
It contains only one method setSession.
The struts 2 framework passes the instance of org.apache.struts2.dispatcher.SessionMap. It extends the java.util.AbstractMap class which implements the java.util.Map.SessionMap. There are many useful methods of SessionMap class.
Methods of SessionMap class
The commonly used methods of SessionMap class are as follows:
Example of SessionAware interface
This example contains three links login, logout and profile. You cannot click on the profile page untill you are logged in. After getting logged in, you may go to the profile page. If the end user clicks on the logout link, he will not be able to access the profile page.
Steps are as follows:
1) Add struts and servlet library
You need to add struts 2 and servlet library.
2) Create index.jsp for input
This jsp page creates three links for login, logout and profile.index.jsp
3) Define action and result in struts.xml
This xml file defines one package and 4 actions. Each action defines at least one result page.
For the loginprocess and logout actions, we are using the same action class but there invocation methods are different.struts.xml
4) Create the action class for login and logout
This action class implements the SessionAware interface and overrides the setSession method to store the information in the session scope.
For logout, we are simply calling the invalidate() method of SessionMap.Login.java
5) Create the Profile class
This class gets the information from the session scope, if any information is found in the session scope with login name, it returns success otherwise false.Profile.java
6) Create view components
There are many view components:
view components for loginlogin.jsp
This page creates the login form.login-success.jsp
This page prints the welcome message with the username.login-error.jsp
This page displays the error message.
view components for logoutlogout-success.jsp
This page simply displays the successfully logged out message.
view components for profileprofile-success.jsp
This page prints the welcome to profile message.profile-error.jsp
This page prints the message to login first and includes the login.jsp page.
If you click on the profile link, you will be forwarded to profile-error.jsp
Now write your name for name and admin for the password.
Now, you are successfully logged in
Now, click on the profile.
Recommended topicLogin and Logout Example with Oracle database