Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Login and Logout Example
3.
Steps 
4.
Inx.jsp Creation
5.
Struts.xml For Action And Result
6.
Login.java For Login And Logout
7.
Logindao.java For Authentication Of The User
8.
Profile.java To Check User Status
9.
Creating Viewpoints
9.1.
View Components For Log-in
9.2.
View Components For Logout 
9.3.
View Components For The Profile
10.
Frequently Asked Questions
10.1.
Which interface is used while creating a login and logout application?
10.2.
Who developed Struts2?
10.3.
What is the need for an account on the application?
10.4.
What is a web application?
10.5.
What are the steps to create a login and logout application?
11.
Conclusion
Last Updated: Mar 27, 2024
Easy

Struts 2 Login and Logout Example

Author Ankit Kumar
0 upvote

Introduction

Struts is an open-source Java framework that Apache designs. Apache provides users a free source to download Struts. Struts follow MVC architecture; Struts also consist of models: Model0, Model1, and Model2. It provides execution of MVC architecture 

Login and Logout

Most of the applications ask the user to log in. In this way, they provide a personalised user experience. An account is a section in which user update their personal details and choices. So, through the data provided by the user's account, the company provides the user with a personalised experience. This blog will provide the knowledge to create a login and logout.

Login and Logout Example

While creating the login and logout application, we are going to use SessionAware interface. We will give session scope information through SessionAware, and ServletActionContext class will be used to acquire the information from the session scope. 

This example has three links: login, logout, and profile. The end user cannot access the profile page unless he or she is logged in. Users may access the profile page after logging in. The end user will be unable to view the profile page if he clicks on the logout page.

Firstly we will consider a table ninja100 in the oracle database. The query of the table is as follows:

CREATE TABLE  "NINJA100"   
   (    "ID" NUMBER,   
    "NAME" VARCHAR2(4000),   
    "PASSWORD" VARCHAR2(4000),   
    "EMAIL" VARCHAR2(4000),   
     CONSTRAINT "NINJA100_PK" PRIMARY KEY ("ID") ENABLE  
   )  

Steps 

  1. inx.jsp for links to logout and login page.
  2. struts.xml to define the result and action.
  3. Login.java to define login and logout logic.
  4. LoginDao.java for cross-checking username and password in the database.
  5. Profile.java to check whether the user is logged out or not.
  6. View components for displaying results.
Login and logout

Inx.jsp Creation

Creating a page with three links for Login, Logout and Profile.

inx.jsp
<hr/>  
<a href="login">login</a>|  
<a href="logout">logout</a>|  
<a href="profile">profile</a>  

Struts.xml For Action And Result

This xml file has a single package and four activities. At least one result page is defined for each activity. 

We use the same action class for the login process and logout actions, but their invocation methods are different.

struts.xml
<?xml version="1.0" encoding="UTF-8" ?>  
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD  
 Struts Configuration 2.1//EN"   
"http://struts.apache.org/dtds/struts-2.1.dtd">  
<struts>  
<package name="abc" extends="struts-default">  
  
<action name="login">  
<result >login.jsp</result>  
</action>  
  
<action name="loginprocess" class="com.codingninjas.Login">  
<result name="success"  >loginsuccess.jsp</result>  
<result name="error" >loginerror.jsp</result>  
</action>  
  
<action name="logout" class="com.codingninjas.Login" method="logout">  
<result name="success" >logoutsuccess.jsp</result>  
</action>  
  
<action name="profile" class="com.codingninjas.Profile">  
<result name="success" >profilesuccess.jsp</result>  
<result name="error" >profileerror.jsp</result>  
</action>  
  
</package>  
</struts>     

Login.java For Login And Logout

In this action class, we implement the SessionAware interface and override the setSession function to save data to the session scope. 

We use the invalidate() function of SessionMap to logout.

Login.java
package com.codingninjas;  
  
import java.util.Map;  
import org.apache.struts2.dispatcher.SessionMap;  
import org.apache.struts2.interceptor.SessionAware;  
  
public class Login implements SessionAware{  
private String username,userpass;  
SessionMap<String,String> sessionmap;  
  
public String getUsername() {  
    return username;  
}  
  
public void setUsername(String username) {  
    this.username = username;  
}  
  
public String getUserpass() {  
    return userpass;  
}  
  
public void setUserpass(String userpass) {  
    this.userpass = userpass;  
}  
  
public String execute(){  
    if(LoginDao.validate(username, userpass)){  
        return "success";  
    }  
    else{  
        return "error";  
    }  
}  
  
public void setSession(Map map) {  
    sessionmap=(SessionMap)map;  
    sessionmap.put("login","true");  
}  
  
public String logout(){  
    sessionmap.invalidate();  
    return "success";  
}  
  
}  

Logindao.java For Authentication Of The User

Here the user’s data will be cross-checked from the oracle database.

LoginDao.java
package com.codingninjas;   
import java.sql.Connection;  
import java.sql.DriverManager;  
import java.sql.PreparedStatement;  
import java.sql.ResultSet;    
public class LoginDao {    
public static boolean validate(String username,String userpass){  
 boolean status=false;  
  try{  
   Class.forName("oracle.jdbc.driver.OracleDriver");  
   Connection con=DriverManager.getConnection(  
   "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");  
     
   PreparedStatement ps=con.prepareStatement(  
     "select * from ninja100 where name=? and password=?");  
   ps.setString(1,username);  
   ps.setString(2,userpass);  
   ResultSet rs=ps.executeQuery();  
   status=rs.next();  
  }catch(Exception e){e.printStackTrace();}  
 return status;  
}  
}  

Profile.java To Check User Status

This class retrieves information from the session scope; if any information with the login name is discovered in the session scope, it returns success; otherwise, it returns false.

Profile.java
package com.codingninjas;  
  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpSession;  
import org.apache.struts2.ServletActionContext;  
  
public class Profile {  
  
public String execute(){  
HttpServletRequest request=ServletActionContext.getRequest();  
HttpSession session=request.getSession();  
  
String s=(String)session.getAttribute("login");  
if(s!=null && !s.equals("")){  
    return "success";  
}  
else{  
    return "error";  
}    
}  
}  

Creating Viewpoints

Following are the viewpoints we are going to create :

  • login.jsp
  • login_success.jsp
  • login_error.jsp
  • logout_success.jsp
  • profile_success.jsp
  • profile_error.jsp

View Components For Log-in

  1. Login.jsp

This code to create the login form.

<jsp:include page="index.jsp"></jsp:include>  
<hr/>  
<%@ taglib uri="/struts-tags" prefix="s" %>  
  
<s:form action="loginprocess">  
<s:textfield name="username" label="Name"></s:textfield>  
<s:password name="userpass" label="Password"></s:password>  
<s:submit value="login"></s:submit>  
</s:form>  


2. Login_success.jsp

This code to print the welcome message with the username.

<jsp:include page="index.jsp"></jsp:include>  
<hr/>  
<%@ taglib uri="/struts-tags" prefix="s" %>  
  
<br/>Welcome, <s:property value="username"/>  


3. Login_error.jsp

This code to display the error message.

Sorry username or password error!  
<jsp:include page="login.jsp"></jsp:include>  

View Components For Logout 

  1. Logout_success.jsp

This page simply displays the successfully logged-out message.

<jsp:include page="index.jsp"></jsp:include>  
<hr/>  
You are successfully logged out!  

View Components For The Profile

  1. Profile_success.jsp

This page prints the welcome-to-profile message.

<jsp:include page="index.jsp"></jsp:include>  
<hr/>  
<br/>Welcome to profile  

2. Profile_error.jsp

This page prints the message to login first and includes the login.jsp page.

Please login first to see profile  
<jsp:include page="login.jsp"></jsp:include>  

 

Must Read Apache Server

Frequently Asked Questions

Which interface is used while creating a login and logout application?

SessionAware interface is used while creating a login and logout application.

Who developed Struts2?

The Apache software foundation developed it.

What is the need for an account on the application?

In this way, they provide a personalised user experience. An account is there in which user update their details and choices what kind of content they expect. So, through the data provided by the user's account, the company provides the user with a personalised experience.

What is a web application?

A web application is an application program that exists on remote servers and is used by the user through the internet. 

What are the steps to create a login and logout application?

Firstly we create inx.jsp for links to logout and login page. Then we create struts.xml to define the result and action. After that we create Login.java to define login and logout logic. Then we create LoginDao.java for cross-checking username and password in the database. Then we create Profile.java to check whether the user is logged out or not. At the end View components for displaying results.

Conclusion

In this blog, we have extensively discussed the process of making login and logout applications in struts. We saw first that we needed to select a database. Then we went through the code and how to create different classes and methods. Then we learnt different viewpoints, and in the end, we discussed some of the frequently asked questions related to this.

Refer to our guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc. Enrol in our courses and refer to the mock test and problems available. Take a look at the interview experiences and interview bundle for placement preparations.

Do upvote our blog to help other ninjas grow. 

Thankyou image
Live masterclass