Login/Logout With Session
In this section, we are going to develop a login/logout application with session. This application checks the user authentication. Whenever you run, it takes a user id and a password (Both the user id and password is "admin") it displays the welcome page, when both fields are correctly filled.
Create an action mapping in the struts.xml file. Here is the code to be added in the struts.xml:
<action name="login" class="net.roseindia.loginAction" > <result name="success" type="dispatcher">/pages/uiTags/Success.jsp</result> <result name="error" type="redirect">/pages/uiTags/Login.jsp</result> </action> <action name="logout" class="net.roseindia.logoutAction" > <result name="success" type="redirect">/pages/uiTags/checkLogin.jsp</result> </action> |
Develop an action class that handles the login request. The Struts 2 framework provides a base ActionSupport class that implements commonly used framework interfaces. In our action class (loginAction.java) we have extended ActionSupport class.
Here is the code of "loginAction" action class:
package net.roseindia;
|
Again, develop an action class to handle the logout operation. An action class (logoutAction) we have extended ActionSupport class.
Here is the code of logoutAction
action class:
package net.roseindia;
|
Develop Login Form: The GUI of the application consists of login form (Login.jsp). The "Login.jsp" displays the login page to the user.
Here is the code of Login.jsp file:
<%@ taglib prefix="s" uri="/struts-tags" %>
|
The "Success.jsp" page displays the Login Success message (Welcome, you have logged-in.) and session (Session Time: Wed Aug 01 11:26:38 GMT+05:30 2007 and Logout ) when user gets successful authentication. If you click the "Logout" then again login page is displayed on the screen.
Here is the code of Success.jsp file:
<%@ taglib prefix="s" uri="/struts-tags" %> <%@ page language="java" contentType="text/html" import="java.util.*"%> <jsp:include page="/struts2tags/pages/uiTags/loginCheck.jsp" /> <html> <head> <title>Welcome, you have logined!</title> </head> <body> Welcome, you have logined. <br /> <b>Session Time: </b><%= new Date(session.getLastAccessedTime())%> <br /><br /> <a href="<%= request.getContextPath() %>/roseindia/logout.action">Logout</a> <br /> </body> </html> |
This page logs out the valid user.
checkLogin.jsp
<%@ taglib prefix="s" uri="/struts-tags" %> <%@ page language="java" contentType="text/html" import="java.util.*"%> <html> <head> <title>Check validate!</title> </head> <body> <s:if test="#session.login != 'admin'"> <jsp:forward page="/pages/uiTags/Login.jsp" /> </s:if> </body> </html> |
Output:
Run this application by getting the login page:
Enter the wrong user id and password in the login page
You get the following output:
Enter the correct user id and password in the login page:
You get the following output:
After clicking the "Logout". You get the following output: