An attribute in servlet is an object that can be set, get or removed from one of the following scopes:
- request scope
- session scope
- application scope
The servlet programmer can pass informations from one servlet to another using attributes. It is just like passing object from one class to another so that we can reuse the same object again and again.
Attribute specific methods of ServletRequest, HttpSession and ServletContext interface
There are following 4 attribute specific methods. They are as follows:
- public void setAttribute(String name,Object object):sets the given object in the application scope.
- public Object getAttribute(String name):Returns the attribute for the specified name.
- public Enumeration getInitParameterNames():Returns the names of the context’s initialization parameters as an Enumeration of String objects.
- public void removeAttribute(String name):Removes the attribute with the given name from the servlet context.
|
Example of ServletContext to set and get attribute
In this example, we are setting the attribute in the application scope and getting that value from another servlet. |
DemoServlet1.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class DemoServlet1 extends HttpServlet{
public void doGet(HttpServletRequest req,HttpServletResponse res)
{
try{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
ServletContext context=getServletContext();
context.setAttribute("company","IBM");
out.println("Welcome to first servlet");
out.println("visit");
out.close();
}catch(Exception e){out.println(e);}
}}
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class DemoServlet2 extends HttpServlet{
public void doGet(HttpServletRequest req,HttpServletResponse res)
{
try{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
ServletContext context=getServletContext();
String n=(String)context.getAttribute("company");
out.println("Welcome to "+n);
out.close();
}catch(Exception e){out.println(e);}
}}
s1
DemoServlet1
s1
/servlet1
s2
DemoServlet2
s2
/servlet2
Leave A Comment