In our last posts, we have learned
JSP implicit objects REQUEST with example,
JSP implicit objects OUT with example,
JSP Implicit Object CONFIG with example ,
JSP Implicit object session with example ,
JSP implicit object PageContext with example,
JSP implicit object RESPONSE with example,
JSP implicit object application is an object of type javax.servlet.http.ServletContext.
The application object belongs to all the JSP pages within the web application.
Difference between config and application object :
1) config object (as explained in earlier post) belongs to a particular JSP page within the web application whereas application object belongs to the all the JSP pages within the web application.
application object is used when some information needs to be shared to all the JSP pages within the application.
Basic example of the same are :
1) Website Visit Counters
2) Admin Name and Id
If any one JSP updates some application values, it will be visible to all the JSP pages.
Methods of implicit object application
1) getAttribute(String name)
2) getAttributeNames
3) setAttribute(String objName, Object object)
4) removeAttribute(String objName)
Declaring variable in deployment descriptor(web.xml) :
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>JSPProject</display-name> <context-param> <param-name>adminName</param-name> <param-value>John</param-value> </context-param> </web-app>
JSP page using application object:
<%@ 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>Insert title here</title> </head> <body> <% String adminName = (String) application.getAttribute("adminName"); out.println("Welcome " + adminName); %> </body> </html>
No comments:
Post a Comment