Table of contents
1.
📌Introduction
2.
📌Aware Interfaces
3.
📌Action class
4.
📌Application of ServletContextAware Interface
5.
📌Example of ServletContextAware
6.
📃Index.jsp
7.
📃Struts.xml
8.
📃StoreData.java
9.
📃GetData.java
10.
📃StoreDataSuccess.jsp
11.
📃GetDataSuccess.jsp
12.
📃GetDataError.jsp
13.
Frequently Asked Questions
13.1.
What do Aware interfaces do?
13.2.
How many different types of Aware interfaces are there?
13.3.
What is the purpose of the ServletContextAware interface?
13.4.
What is the benefit of importing the Action interface?
14.
Conclusion
Last Updated: Mar 27, 2024
Medium

ServletContextAware Interface Example

📌Introduction

As we know Struts lets us create web applications using servlet and JSP. Now we will talk about one of the useful features of struts2; interfaces. Interfaces in general have abstract methods without the body and static constants.

Struts2

We implement these interfaces in  a class and then provide body to the methods. Struts2 Aware interfaces help us to insert data into a request, response, context, or session object. There are four Aware interfaces. Through this blog, we will focus on learning the servletContextAware interface.

📌Aware Interfaces

First let us briefly see what all the four interfaces do.

Aware interfaces

 

  1. SessionAware: Actions that need access to the user's HTTP session attributes should implement this interface. 
     
  2. ServletContextAware: The Action class must implement the ServletContextAware interface to save information in the application scope. 
     
  3. ServletRequestAware: All action classes that want to access the servlet request object should implement this interface.
     
  4. ServletResponseAware: Defines an object that can let a servlet respond to the client.

 

The action class must implement all the Aware interfaces to hold information that may be obtained from other action classes. 

📌Action class

Action classes are the ones that respond to the users actions. They decide what will Struts render for the user to view. The action class in struts 2 is POJO (Plain Old Java Object). 

POJO signifies that we do not need to implement interfaces or extend classes.

An execute() method defines the business logic. The following is an example of an action class:
 

import com.opensymphony.xwork2.Action;  
public class ActionExample 
{  
	public String execute()
	{ 
		return SUCCESS; //SUCCESS is one of the five constants that can be
      					// returned from the action class  
	}  
}
You can also try this code with Online Java Compiler
Run Code

 

Now that we know what an action class is, let us understand the ServletContextAware interface. 

The Action class must implement the ServletContextAware interface to save the data in the application scope.

It just has one method, setServletContext(ServletContext context)

Syntax: 

public void setServletContext(ServletContext context);
You can also try this code with Online Java Compiler
Run Code

📌Application of ServletContextAware Interface

The ServletContextAware interface has a wide range of potential applications. They are as follows:

  • We may use a collection to contain all the records of a table in the ServletContext object and get this information from any action class. The web application's performance will improve as a result.
     
  • We may save the Connection object and get it from any action class.

📌Example of ServletContextAware

In the example, we will make two links: one to the first page, Store Data, and one to the second page Get Data. If we click directly on the second page, no data will display, but if we first click on the first link(Store Data), data gets stored in the ServletContext object and may be retrieved from another action class. The second link(Get Data) retrieves data from the ServletContext object.
 

For this example, we will create the following files: 

xml,java and jsp files

 

Index.jsp - This will provide connections to the first and second actions.

Struts.xml - It will define the outcome and action.

StoreData.java - For saving data in the ServletContext object.

GetData.java - To retrieve data from the ServletContext object.

StoreDataSuccess.jsp, GetDataSuccess.jsp and GetDataError.jsp - For displaying the results.

Now let us create all of the files mentioned above one by one.

 

📃Index.jsp

This JSP file generates two links, the first executing the first action class and the second invoking the second action class.

 

<hr/>  
<a href="StoreDataPage">Store Data</a>
<a href="GetDataPage">Get Data</a>  
<hr/>

📃Struts.xml

xml

In this file, we define two actions and results.
 

<?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="package1" extends="struts-default">  
<action name="StoreDataPage" class="com.Coding Ninjas Studio.StoreData">  
<result>StoreDataSuccess.jsp</result>  
</action>  
  
<action name="GetDataPage" class="com.Coding Ninjas Studio.GetData">  
<result>GetDataSuccess.jsp</result>  
<result name="error">GetDataError.jsp</result>  
</action>  
  
</package>  
</struts> 

📃StoreData.java

java

This action class implements the ServletContextAware interface and overrides the setServletContext function to save data in the application scope.

 

package com.Coding Ninjas Studio;  
import javax.servlet.ServletContext;  
import org.apache.struts2.util.ServletContextAware;    
public class StoreData implements ServletContextAware
{
	public void setServletContext(ServletContext c) 
	{
		c.setAttribute("object1","hello");  
    }
	public String execute()
	{  
         return "success";  
    }  
}
You can also try this code with Online Java Compiler
Run Code

📃GetData.java

java

This class will retrieve the data from the application scope. If any data with the login name is present in the session scope, it returns success; else, it returns an error.
 

package com.Coding Ninjas Studio;  
import javax.servlet.ServletContext;  
import org.apache.struts2.ServletActionContext;  
public class GetData
{  
	public String execute()
	{  
		ServletContext c=ServletActionContext.getServletContext();  
        String ob=(String)c.getAttribute("object1");  
        if(ob!=null)
		{  
             return "success";  
        }  
         else
		{  
        	return "error";  
        }  
	}  
}
You can also try this code with Online Java Compiler
Run Code

 

Must Read Apache Server

📃StoreDataSuccess.jsp

jsp

This is one of the three view components. This file will create the login form.

 

<jsp:include page="Index.jsp"></jsp:include>  
<%@ taglib uri="/struts-tags" prefix="s" %>  
Hello user, data is set(saved) into the ServletContext object. 
<br/>  
Now you may click the second page to verify if the data is set or not.
<br/>  
Data is :<s:property value="#application.object1"/>

📃GetDataSuccess.jsp

This is the second view component. This page displays the welcome message along with the username.


<jsp:include page="Index.jsp"></jsp:include>  
<%@ taglib uri="/struts-tags" prefix="s" %>  
Hello! The data is available.<br/>  
Data is :<s:property value="#application.object1"/>

📃GetDataError.jsp

This third view component displays the error message if the data is not set.
 

<jsp:include page="index.jsp"></jsp:include>  
Sorry. The data is not set in the ServletContext object, so it is not retrieved.

You can also read What is Servlet here.

Frequently Asked Questions

What do Aware interfaces do?

They help us to insert data into a request, response, context, or session object.

How many different types of Aware interfaces are there?

There are four types of Aware interfaces which are SessionAware, ServletContextAware, ServletRequestAware, and ServletResponseAware interface.

What is the purpose of the ServletContextAware interface?

It can help in containing all the records of a table in the ServletContext object and get this information from any action class. We can also save the Connection object and get it from any action class.

What is the benefit of importing the Action interface?

If we implement the Action interface, we can directly use any of the five constants it provides instead of values.

Conclusion

By using the struts2 framework, we can create MVC-based Java web applications. Through this blog, we learned what an Aware interface is and its types. We also learned the purpose of an action class. We discussed in detail about ServletContextAware interface through an example by creating the XML, java, and JSP files. 

Are you looking for something else? You name it, and we have it. Be it frontend technologiesbackend technologiesbig data, and many more topics; code studio got you covered. Do check out the website!

Live masterclass