Thursday, 13 November 2014

jsp application implicit object

application is an implicit object of type ServletContext.
This object is a bit different.As the name indicates,it is for the whole application.
It is created only once by the web container that can be used on all the jsp pages.
It can be used to get,set and remove the attributes from the application scope.
This object is used to get the initialization parameters declared in the web.xml file(Deployment Descriptor).

Popular Methods of implicit object application

getAttribute(String name)
getAttributeNames
setAttribute(String objName, Object object)
removeAttribute(String objName)
getServerInfo()
getInitParameter(String name)
getInitParameterNames
getResourceAsStream(Path)

Example
 application.getAttribute("attribute1");

ApplicationObjectDemo.jsp 
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Application Object Demo</title>
</head>
<body>
<%
application.setAttribute("Name","Raj");
String getValueApplcation=(String)application.getAttribute("Name");
%>
The value retrieved is <%= getValueApplcation%> <br>
The value retrieved from web.xml is <%= application.getInitParameter("User")%>
</body>
</html>
web.xml
....
<context-param> 
<param-name>User</param-name> 
<param-value>Supervisor</param-value> 
</context-param> 
...
output