Introduction
This article explains servlet attributes in Java. The NetBeans IDE is used to develop the sample.
What is Servlet Attribute
Attributes are the objects that can be used to set, get or delete (removed) from one of the following scopes:
- application scope
- session scope
- request scope
The Servlet attribute is used mainly to pass the information from one servlet to another or from one filter to another, etcetera. It is just like passing an object from one class to another so that we can reuse the same object again and again.
Some common public methods of servlet attributes are:
- Object getAttribute(String name)
Returns the attribute object for the specified name.
- void setAttribute(String name, Object object)
Sets the given object in the application scope.
- Enumeration getInitParameterNames()
Returns the names of the context's initialization paramters as an Enumeration of String objects.
- void removeAttribute(String name)
Removes the attribute with the given name from the servlet context.
Example
In this example, we are creating two servlets named "ServletOne" and "ServletTwo". In ServletOne we set the attribute that was passed and in ServletTwo we get this attribute and display it on the web server.
The following procedure is required for this.
Step 1
Open the NetBeans IDE.

Step 2
Select "Java web" -> "Web application".

Step 3
Type your project name as "ServletAttributeDemo" as in the following:

Step 4
Click on "Next" and choose your server as in the following:

Step 5
Now delete your default index.jsp file. Create a new Servlet file using the following.
Right-click on the project menu then select "New" -> "Servlet" as in the following:

Step 6
Type your servlet name as "ServletOne" as in the following:

Step 7
Click on "Finish" and provide the following code for it.
ServletOne.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
@WebServlet(urlPatterns = {"/ServletOne"})
public class ServletOne extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) {
try {






Join the conversation! Your thoughts help the community grow.