< Prev
Next >

ServletContext Attributes

In this article, we are going to understand how to associate attributes with a ServletContext object. An attribute is an object and when such objects are associated with a ServletContext object, they are called context attributes and are available to the whole application i.e. all the Servlets in the application can access these attributes through the ServletContext object. These context attributes are stored in the context scope on the server side used for the request processing.

We can set and get the value of context attributes associated with the ServletContext object by using the methods of ServletContext interface. After setting some attributes with the ServletContext object, we can even access these attributes from one to another Servlet in order to have a shared request processing by multiple Servlets.

Methods of ServletContext to set,get and remove context attributes

Method Description
Object getAttribute(String str) This method gets an individual context attributes.
Enumeration getAttributesNames() This method gets all the named of context attributes.
void setAttribute(String name, Object value) This method sets the context attributes.
void removeAttribute(String name) This method sets the context attributes.

A Request Attribute Example

We are creating a webpage which asks the user to submit asking the user to enter the name and percentage at high school to know if he/she is eligible to get a scholarship at an university or not, based on a condition -

after filling the details when submit button is clicked, the request is are dispatched or forwarded to the Servlet named FirstServlet (mentioned in the deployment descriptor file(web.xml).


<title>  Context Attributes Demo </title>

<b>Please enter your details to know if you are eligible to apply for scholarship at our university.</b>

<form action = "FirstServlet">
Name :<input type = "text"  name = "username"/>

Percentage :<input type = "text"  name = "percentile"/>

<input type = "submit" value = "submit" />


Creating a Servlet to set request attributes

We are creating a Servlet extending GenericServlet abstract class. GenericServlet class implements Servlet and ServletConfig interface, hence we can directly call the methods of ServletConfig within this Servlet.

Please Subscribe

Please subscribe to our social media channels for daily updates.

Decodejava Facebook Page  DecodeJava Twitter Page Decodejava Google+ Page



Please check our latest addition