Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction🤔
2.
SessionAware Interface🎯
2.1.
SessionAware interface example🧑‍🏫
3.
Frequently Asked Questions
3.1.
What is 'Struts'?
3.2.
What is an HTTP session?
3.3.
What is 'package' in Struts XML?
3.4.
What is Web Framework?
3.5.
What is API?
4.
Conclusion
Last Updated: Mar 27, 2024
Medium

SessionAware Interface Example

Author Sanchit Kumar
0 upvote

Introduction🤔

When dealing with the struts2 application, you might need to access the HTTP session object. Your action class should implement the SessionAware interface provided by struts 2 to obtain a reference to the HTTP session object.

struts

So let us learn about the SessionAware interface.😊

SessionAware Interface🎯

This interface should be implemented by actions that want access to the user's HTTP session attributes. Implementing this interface will give actions access to a map where they can put objects which can be made available to subsequent requests.

Method

void setSession(Map<String,Object> session

 

Description

The SessionMap class instance is passed when the struts framework calls this method.

SessionAware interface example🧑‍🏫

In this example, we will make a JSP page with three links for the user. From there, the user will be redirected to various pages depending upon action on various links.

First, set up the basic struts web application and name it sessionaware_interface.

Step1🧑‍💻 - Create a JSP page and name it as index.jsp

index.jsp

<!DOCTYPE html>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
	<body>
		<h1>Struts2 SessionAware Interface Example</h1>
		<ul>
			<li><a href="loginpage">LogIn</a></li>
			<li><a href="userlogout">LogOut</a></li>
            <li><a href="userprofile">UserProfile</a> </li>
		</ul>
	</body>
</html>


Step2⭐ - Handle various actions of the user and corresponding responses in struts.xml

struts.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
  <constant name="struts.devMode" value="true"></constant>  
  <package name="com.sessionaware_interface" extends="struts-default" >  

    <action name="loginpage">  
      <result>login.jsp</result>  
    </action>  

    <action name="userlogin" class="com.sessionaware_interface.Login" method="execute"> 
      <result name="success">/login-success.jsp</result>  
      <result name="userlogin">/login-error.jsp</result>  
    </action>  

    <action name="userlogout" class="com.sessionaware_interface.Login" method="userlogout">
      <result name="success">/logout-success.jsp</result>  
    </action>  
    <action name="userprofile" class="com.sessionaware_interface.Profile" method="execute">
    	<result name="success">/profile-success.jsp</result>  
        <result name="userlogin">/profile-error.jsp</result>  
    </action>  
  </package>  
</struts>


Step3✨ - Create the action class for login and logout, implement SessionAware Interface and to store the information in the session scope override setSession.

inout.java

package com.sessionaware_interface;  
  
import java.util.Map;
import org.apache.struts2.dispatcher.SessionMap;  
import org.apache.struts2.interceptor.SessionAware;  

public class Login implements SessionAware{
	private String name,password;  
	private SessionMap<String,Object> sessionMap;  
	@Override  
	public void setSession(Map<String, Object> map) {  
	    sessionMap=(SessionMap)map;  
	}
	public String execute(){  
	    if(password.equals("admin")){  
	        sessionMap.put("userlogin","true");  
            sessionMap.put("username",name);  
            return "success";
	    }
	    else{  
	        return "userlogin";  
	    }  
	    
	}  
	public String logout(){  
	    if(sessionMap!=null){  
	        sessionMap.invalidate();  
	    }  
	    return "success";  
	}
}
You can also try this code with Online Java Compiler
Run Code


Step4✨ - Create the profile class to fetch information from the session scope.

profile.java

package com.sessionaware_interface;  
  
import javax.servlet.http.HttpSession;  
import org.apache.struts2.ServletActionContext;  

public class Profile{  
    public String execute(){  
        HttpSession session=ServletActionContext.getRequest().getSession(false);  
        if(session==null || session.getAttribute("userlogin")==null){  return "userlogin";  
        }  
        else{  
            return "success";  
        }  
    }  
}
You can also try this code with Online Java Compiler
Run Code

 

Step5🧑‍🎨 - Create the following JSP pages[View Components].

  • login.jsp - for the login page.
  • login-success.jsp - to show the welcome message with username after login.
  • login-error.jsp - to show an error message while logging.
  • logout-success.jsp - to show message after logout.
  • profile-success.jsp - to show the welcome message on the profile page.
  • profile-error.jsp - to show the error message if the user tries to visit the profile page without inputting credentials.

 

login.jsp

<!DOCTYPE html>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<body>
 <s:form action="userlogin">  
    <s:textfield name="username" label="UserName"></s:textfield>  
 <s:password name="password" label="Password"></s:password>  
 <s:submit value="userlogin"></s:submit>  
 </s:form>  
</body>
</html>


login-success.jsp

<!DOCTYPE html>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
      <body>
            <jsp:include page="index.jsp"></jsp:include>  
            <hr>
    	      Welcome, Ninja - <s:property value="#session.name"/>  
	</body>
</html>


login-error.jsp

<!DOCTYPE html>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
	<body>
            <jsp:include page="index.jsp"></jsp:include>  
            <hr>  
            Sorry Ninja, username/password Error!  
            <jsp:include page="login.jsp"></jsp:include>
	</body>
</html>


logout-success.jsp

<!DOCTYPE html>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
	<body>
		<jsp:include page="index.jsp"></jsp:include>  
            <hr>  
            Ninja, you are successfully logged out! 
	</body>
</html>


profile-success.jsp

<!DOCTYPE html>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
	<body>
		<jsp:include page="index.jsp"></jsp:include>  
            <hr>
            Welcome to Profile, Ninja - <s:property value="#session.name"/>  
	</body>
</html>


profile-error.jsp

<!DOCTYPE html>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
	<body>
		<jsp:include page="index.jsp"></jsp:include>  
            <hr>  
            Sorry Ninja, username/password Error!  
            <jsp:include page="login.jsp"></jsp:include> 
	</body>
</html>


Step6🕸 - Make changes to the web.xml file.

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	id="WebApp_ID" version="2.5">
	<display-name>sessionaware_interface</display-name>
	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
	<filter>
		<filter-name>struts2</filter-name>
		<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>struts2</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
</web-app>


Step7 - Execution🦾

Start the server and hit the given below URL

 

URL👉 - http://localhost:8080/sessionaware_interface/ 

Response💫 - 

index page

 

Now click on the UserProfile you will get redirected to URL
👉 - http://localhost:8080/sessionaware_interface/profile 
Response💫 - 

userprofile response

Input username and password - 

input username and password

 

Click on the Login you will get redirected to URL
👉 - http://localhost:8080/sessionaware_interface/login 

Response💫 - 

login response


Click on the UserProfile you will get redirected to URL
👉 http://localhost:8080/sessionaware_interface/profile 
Response💫 - 

userprofile response


Click on the LogOut you will get redirected to URL
👉 http://localhost:8080/sessionaware_interface/logout 
Response💫 - 

logout response

 

Must Read Apache Server

Frequently Asked Questions

What is 'Struts'?

Struts is a free, open-source framework for web applications written in Java. Apache Software Foundation maintains this framework.

What is an HTTP session?

A session is described as a series of related browser requests made by the same client in a certain time period.

What is 'package' in Struts XML?

Packages are a logical configuration unit that can be used to group actions, results, result types, interceptors, and interceptor stacks.

What is Web Framework?

It is a software framework, also known as a web application framework (WAF), which helps in the creation of web applications, including web APIs, web services and web resources.

What is API?

API (Application Programming Interface) is a means of communication between two or more computer programs. It is a kind of software interface that provides a service to other software programs.

Conclusion

In this article, we discussed the implementation of the SessionAware Interface provided by Struts2 with an example.

See the official website for documentation and other information about Struts, and to learn about various Java frameworks, click here.

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.

Happy Learning Ninja! 🥷

coding ninjas
Live masterclass