logo

Attribute In Servlet


Show

An attribute in servlet is an object which will be set, get or faraway from one among the subsequent scopes:

  1. request scope
  2. session scope
  3. application scope

The servlet programmer can pass information from one servlet to a different one using attributes. it's a bit like passing an object from one class to a different one in order that we will reuse an equivalent object again and again.

Attribute specific methods of ServletRequest, HttpSession and ServletContext interface

There are 4 attribute specific methods. they're as follows:

  1. public void setAttribute(String name,Object object): sets the given object within the application scope.
  2. public Object getAttribute(String name): Returns the attribute for the required name.
  3. public Enumeration getInitParameterNames(): Returns the names of the context's initialization parameters as an Enumeration of String objects.
  4. public void removeAttribute(String name): Removes the attribute with the first name from the servlet context.

Example of ServletContext to line and obtain attribute

In this example, we are setting the attribute within 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("<a href='servlet2'>visit</a>");  

out.close();   

}catch(Exception e){out.println(e);}    

}}  

DemoServlet2.java

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);}  
}}  

Web.xml

<web-app>   

<servlet>  
<servlet-name>s1</servlet-name>  
<servlet-class>DemoServlet1</servlet-class>  
</servlet>   

<servlet-mapping>  
<servlet-name>s1</servlet-name>  
<url-pattern>/servlet1</url-pattern>  
</servlet-mapping>   

<servlet>  
<servlet-name>s2</servlet-name>  
<servlet-class>DemoServlet2</servlet-class>  
</servlet>   

<servlet-mapping>  
<servlet-name>s2</servlet-name>  
<url-pattern>/servlet2</url-pattern>  
</servlet-mapping>   

</web-app>

What is the difference between ServletConfig and ServletContext

The servletconfig object refers to the only servlet whereas servletcontext object refers to the entire web application.