SessionAware Interface ExampleThe SessionAware interface must be implemented by the Action class to store the information in the session scope. Method of SessionAware interfaceIt contains only one method setSession.
SessionMap classThe 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 classThe commonly used methods of SessionMap class are as follows:
Example of SessionAware interfaceThis 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 libraryYou need to add struts 2 and servlet library. 2) Create index.jsp for inputThis jsp page creates three links for login, logout and profile. index.jsp3) Define action and result in struts.xmlThis 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.xml4) Create the action class for login and logoutThis 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.java5) Create the Profile classThis 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.java6) Create view componentsThere are many view components:
view components for loginlogin.jspThis page creates the login form. login-success.jspThis page prints the welcome message with the username. login-error.jspThis page displays the error message. view components for logoutlogout-success.jspThis page simply displays the successfully logged out message. view components for profileprofile-success.jspThis page prints the welcome to profile message. profile-error.jspThis page prints the message to login first and includes the login.jsp page. OutputIf 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 |