What is servlet context and what it takes actually as parameters?

Showing Answers 1 - 6 of 6 Answers

John

  • Jun 3rd, 2005
 

Servlet context is an object which is created as soon as the Servlet gets initialized.Servlet context object is contained in Servlet Config. With the context object u can get access to specific  
resource (like file) in the server and pass it as a URL to be displayed as a next screen with the help of RequestDispatcher 
eg :- 
 
ServletContext app = getServletContext(); 
RequestDispatcher disp; 
if(b==true) 
disp = app.getRequestDispatcher 
("jsp/login/updatepassword.jsp"); 
else 
disp = app.getRequestDispatcher 
("jsp/login/error.jsp"); 
 
this code will take user to the screen depending upon the value of b. 
 
in ServletContext u can also get or set some variables which u would  
like to retreive in next screen. 
eg 
context.setAttribute("supportAddress", "temp@temp.com");  
 
Better yet, you could use the web.xml context-param element to  
designate the address, then read it with the getInitParameter method  
of ServletContext. 
 
There are some methods in context object with the help of which u can  
get the server (or servlet container) information. 
 
Apart from all this with the help of ServletContext u can implement  
ServletContextListener and then use the get-InitParametermethod to  
read context initialization parameters as the basis of data that will  
be made available to all servlets and JSP pages. 

  Was this answer useful?  Yes

Sumit Sengar

  • Aug 22nd, 2005
 

Another very important and practical application of ServletContext that i have come across is that it can be used to hold the object which can generate request independent and non-static data. Suppose we want that our servlet should dispaly a particular piece of info from the server everytime it displays the page regardless of the user who placed the request.

  Was this answer useful?  Yes

Aparna

  • May 5th, 2006
 

Sumit Sengar Wrote: Another very important and practical application of ServletContext that i have come across is that it can be used to hold the object which can generate request independent and non-static data. Suppose we want that our servlet should dispaly a particular piece of info from the server everytime it displays the page regardless of the user who placed the request.

  Was this answer useful?  Yes

You cannot set the attribute of the servletcontext,

You can only call the getAttribute() of the servletContext object.
The attribute of the servletContext can be set in the web.xml file using 
<context-param>
<param-name></param-name>
<param-value></param-value>
</context-param>

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions