Servlet Tutorials

Attribute in Servlet
Previous Home Next
adplus-dvertising

In servlet an object that can be set, get or removed from one of the following scopes

  1. request
  2. session
  3. application

In the servlet programmer which can be a pass informations of servlet to another using attributes.

Servlet attributes is provided a passing object from one class to another so that we can reuse the same object again and again.

Servlet attribute specific methods of ServletRequest, HttpSession and ServletContext interface

Servlet attribute specific four methods as follows:

  1. public void setAttribute(String name,Object object):It is sets the given object in the application scope.
  2. public Object getAttribute(String name):It is returns the attribute for the specified name.
  3. public Enumeration getInitParameterNames():It is returns the names of the context's initialization parameters as an Enumeration of String objects.
  4. public void removeAttribute(String name):It is removes the attribute with the given name from the servlet context.

Example of ServletContext to set and get attribute

Servlet1.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);}
}}
Servlet2.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>
Previous Home Next