Nearby lessons

25 of 30

JSP Examples - Implicit Objects & Scopes

📌 What You Will Learn
  • Use every implicit object in a real JSP
  • Configure error pages two ways
  • Manage attributes across page/request/session/application scopes

Demo programs for the nine JSP implicit objects (request, response, out, session, application, config, page, pageContext, exception), error-page configuration, attribute scopes and JSP Documents.

1) Request and Response Implicit Objects

Example01
JCode Cell
1 
2<h1>The Request Method:<%= request.getMethod() %><br>
3User Name: <%= request.getParameter("user") %><br>
4Client IP Address: <%= request.getRemoteAddr()%><br>
5Content Type:<%= response.getContentType() %>
6</h1>http://localhost:7777/jsp1/request.jsp?user=Sunny
7

2) Application Implicit Object

Example02
JCode Cell
1 
2<h1>
3The context parameter User Name: <%= application.getInitParameter("uname") %><br>
4The Application Name:<%= application.getServletContextName() %>
5</h1>web.xml:
6<web-app>
7<display-name>JSP Implicit Objects Application</display-name>
8<context-param>
9<param-name>uname</param-name>
10<param-value>scott</param-value>
11</context-param>
12</web-app>http://localhost:7777/jsp1/application.jsp
13

3) Session Implicit Object

If we can make session implicit object unavailable by using page directive then we are not allowed

to use session implicit object. otherwise we will get compile time error.

test.jsp:

Example03
JCode Cell
1 
2<h1>
3The Session ID is : <%= session.getId() %> <br>
4The Session Time out is : <%= session.getMaxInactiveInterval() %> Seconds <br>
5Is the session is newly created: <%= session.isNew() %> <br>
6</h1>
7

3) Session Implicit Object

CE: session cannot be resolved.

Q. In which of the following cases session object available in the JSP?

Example04
JCode Cell
1 
2<%@ page session="false" %>
3The Session ID is : <%= session.getId() %>
4

3) Session Implicit Object

Example05
JCode Cell
1 
2<%@ page session="true" %>
3<%@ page session="false" %>
4<%@ page session="true" session="false" %>
5<%@ page contentType="text/html" %>
6

4) Config Implicit Object

config.jsp:

Example06
JCode Cell
1 
2getServletName()
3getInitParameter(String pname)
4getInitParameterNames()
5getServletContext()
6

4) Config Implicit Object

Example07
JCode Cell
1 
2The Logical Name: <%= config.getServletName() %><br>
3

2) The Init Param value is

The Logical Name: DemoJSP

The Init Param value is : UttarPradesh

http://localhost:7777/jsp1/config.jsp

The Logical Name: jsp

The Init Param value is : null

Note: To reflect Servlet level web.xml configurations in the JSP, compulsory we should access by

using url-pattern.

Example08
JCode Cell
1 
2<%= config.getInitParameter("hotTopic") %>web.xml:
3<web-app>
4<servlet>
5<servlet-name>DemoJSP</servlet-name>
6<jsp-file>/config.jsp</jsp-file>
7<init-param>
8<param-name>hotTopic</param-name>
9<param-value>UttarPradesh</param-value>
10</init-param>
11</servlet>
12<servlet-mapping>
13<servlet-name>DemoJSP</servlet-name>
14<url-pattern>/test</url-pattern>
15</servlet-mapping>
16</web-app>http://localhost:7777/jsp1/test
17

2) The Init Param value is

The pageContext implicit object is of type javax.servlet.jsp.PageContext.

It is abstract class and web server vendor is responsible to provide implementation.

PageContext is the child class of JspContext.

JspContextSimple Custom Tag (JSP 2.0 V)

PageContext Classic Custom Tag (JSP 1.1 V)

We can use pageContext implicit object for the following 3 purposes.

Example09
JCode Cell
1 
2pageContext implicit object:
3

2) The Init Param value is

Example10
JCode Cell
1 
2To get all other implicit objects
3To Perform Request Dispatching activities
4To perform attribute management in any scope
5

a) Getting JSP Implicit objects from pageContext

These methods are not useful within the JSP. We can use these methods outside of JSP, mostly in

Custom Tag Handlers.

Example11
JCode Cell
1 
2request getRequest()
3response getResponse()
4config getServletConfig()
5application getServletContext()
6session getSession()
7out getOut()
8page getPage()
9exception getException()
10

b) Request Dispatching by using pageContext

The target resource can be specified by either relative path or absolute path.

Eg:

first.jsp:

Example12
JCode Cell
1 
2public void forward(String target)
3public void include(String target)
4

b) Request Dispatching by using pageContext

<h1>Hello This is Second JSP</h1>

forward:

o/p: Hello This is Second JSP

include:

o/p: Hello This is First JSP

Hello This is Second JSP

Example13
JCode Cell
1 
2<h1>Hello This is First JSP</h1>
3<%
4pageContext.forward("second.jsp");
5%>second.jsp:
6

c) Attribute Management in any scope

This implicit object is of type javax.servlet.jsp.JspWriter.

This class is specially designed for JSPs to write character data to the response.

The main difference b/w JspWriter and PrintWriter is, in PrintWriter buffering concept is not

available. Hence if we are writing anything by using PrintWriter, it will write directly to the

response object.

But in the case of JspWriter, buffer concept is available. Hence if we are writing anything by

using JspWriter, first it will write to buffer and at least total buffered data will write to

response.

Except this buffer difference there is no other difference b/w JspWriter and PrintWriter.

JspWriter = PrintWriter+Buffer

PrintWriter

Response

Object

JspWriter

Buffer

test.jsp:

Example14
JCode Cell
1 
2out implicit object:
3

c) Attribute Management in any scope

o/p:

Sunny

Sunny

Sunny

Mallika

Mallika

Mallika

Note: Within the JSP we can use either PrintWriter or JspWriter but not recommended to use

both simultaneously.

Note:

JspWriter is the child class of Writer(AC).Hence all methods of Writer class are by default

available to the JspWriter through inheritance.

In addition to these methods, JspWriter contains its own set of print() and println() to add any

type of Data to the response.

Writer (AC)write (int ch)

write (char[] ch)

write (String s)

close()

flush()

JspWriter (AC)print()

println()

test.jsp:

Example15
JCode Cell
1 
2<%@ page import="java.io.*" %>
3<%
4PrintWriter pw=response.getWriter();
5out.print("<h1>Mallika</h1>");
6pw.print("<h1>Sunny</h1>");
7out.print("<h1>Mallika</h1>");
8pw.print("<h1>Sunny</h1>");
9out.print("<h1>Mallika</h1>");
10pw.print("<h1>Sunny</h1>");
11%>http://localhost:7777/jsp1/test.jsp
12
Output

<h1>Mallika</h1>
<h1>Mallika</h1>
<h1>Mallika</h1>
      

c) Attribute Management in any scope

Q1. In JSP, How we can write Response?

By using out implicit object, which is of the type : JspWriter

Q2. What is the difference b/w PrintWriter and JspWriter?

Buffer

JspWriter = PrintWriter+Buffer;

Example16
JCode Cell
1 
2<h1>
3<%
4out.print("The PI value is :");
5out.print(3.14);
6out.print("This is exactly ");
7out.print(true);
8%>
9</h1>
10

7) Page Implicit Object

Note: On the page variable we cannot call servlet specific methods. Hence page implicit object is

the most rarely used object in the JSP.

Example17
JCode Cell
1 
2<%= page.getServletInfo() %>
3<%= this.getServletInfo() %>
4<%= getServletInfo() %>
5<%= ((HttpServlet)page).getServletInfo() %>
6

8) Configuring Error Pages in the JSP (Exception Implicit Object)

Example18
JCode Cell
1 
2Declarative Approach
3Programmatic Approach
4

1) Declarative Approach

The error pages configured in this approach are applicable to the entire web application.

Example19
JCode Cell
1 
2<web-app>
3<error-page>
4<exception-type>java.lang.ArithmeticException</exception-type>
5<location>/error.jsp</location>
6</error-page>
7<error-page>
8<error-code>404</error-code>
9<location>/error404.jsp</location>
10</error-page>
11</web-app>
12

2) Programmatic Approach

In demo.jsp if any exception or error occurs then error.jsp is responsible to report this error.

This way of configuring error page is applicable for a particular JSP.

http://localhost:7777/jsp1/demo.jsp

We can declare a JSP as error page by using isErrorPage attribute of page directive.

In the error pages only exception implicit object is available.

error.jsp:

Example20
JCode Cell
1 
2<%@ page errorPage="error.jsp" %>
3<h1> The Result is :<%= 10/0 %></h1>
4

2) Programmatic Approach

If JSP is not declared as error page but if we are trying to access exception implicit object then

we will get compile time error saying-"exception cannot be resolved"

Note: If we are sending the request to error page directly without any exception, then

exception implicit object refers "null"

Which approach is recommended?

Declarative Approach is recommended b'z we can customize error pages based on exception type

and error code.

Note:

  • All JSP Implicit objects are available as local variables of _jspService() method in the Generated

Servlet. Hence inside _jspService() method only we can access implicit objects. But outside of

_jspService() method we cannot access.

Scriptlet and expression tags code will be placed inside _jspService() method. Hence inside

scriptlet and expression tags we can use jsp implicit objects.

But declaration tag code will be placed outside of _jspService() method in the generated servlet.

Hence we cannot use jsp implicit objects inside declaration tag.

Eg 1: <%

out.println("Hello");

%>

Eg 2: <%!

public void m1()

{

out.println("Hello");

}

%>

Eg 3: Session Id: <%= session.getId() %>

  • Among all JSP implicit objects except session and exception, all remaining objects always

available in every JSP. We cannot make these objects unavailable.

session object by default available in every JSP. But we can make it unavailable by using page

directive as follows..

<%@ page session="false" %>

exception implicit object is by default not available in every JSP. We can make it avialble by using

page directive as follows..

<%@ page isErrorPage="true" %>

JSP Scopes

In Servlets we have the following 3 scopes for storing information in the form of attributes...

  • Request Scope
  • Session Scope
  • Application Scope

In addition to these 3 scopes in JSPs, we have page Scope also...

  • Request Scope:

In Servlets this scope is maintained by ServletRequest object but in JSPs, it is maintained by

request implicit object.

The information stored in request scope is available for all the components which are processing

that request.

Request scope will start at the time of request object creation(i.e. just before calling service()

method) and ends at the time of request object destruction(i.e. just after completing service()

method).

Once request processing completed, request scoped attributes will be destroyed.

We can perform attribute management in request scope by using the following methods...

public void setAttribute(String name,Object value)

public Object getAttribute(String name)

public void removeAttribute(String name)

public Enumeration getAttributeNames()

  • Session Scope:

In Servlets session scope is maintained by HttpSession object, but in JSPs session scope is

maintained by session implicit object.

Session scope will be started at the time of session object creation and ends once session expires

either by logout mechanism(invalidate() method) or by timeout mechanism.

The information stored in session scope is available for all components which are participating in

that session.

HttpSession contains the following methods for attribute management in session scope

public void setAttribute(String name,Object value)

public Object getAttribute(String name)

public void removeAttribute(String name)

public Enumeration getAttributeNames()

  • Application Scope:

In Servlets this scope is maintained by ServletContext object, but in JSPs this scope is maintained

by application implicit object.

The information stored in application scope is available for all components of the web application.

Application scope will be started at the time of ServletContext object creation (i.e. at the time of

application deployment or at server startup) and will be ends at the time of context object

destruction(ie at the time of application undeployment or server shutdown)

ServletContext interface defines the following methods for attribute management in application

scope.

public void setAttribute(String name,Object value)

public Object getAttribute(String name)

public void removeAttribute(String name)

public Enumeration getAttributeNames()

Q. Write a JSP to print hit count of the application?

hitcount.jsp:

Example21
JCode Cell
1 
2<%@ page isErrorPage="true" %>
3<h1>currently we are facing some problems plz try after some time..The problem is: <%= exception %></h1>
4

2) Programmatic Approach

Q. Write a JSP to print number of users login into our application?

sessioncount.jsp:

Example22
JCode Cell
1 
2<%
3Integer count=(Integer)application.getAttribute("hitcount");
4if(count==null)
5{
6count=1;
7}
8else
9{
10count++;
11}
12application.setAttribute("hitcount",count);
13%>
14<h1>Hit count of the application is:<%= count %></h1>http://localhost:7777/jsp1/hitcount.jsp
15

2) Programmatic Approach

Q. Write a JSP to display the number of requests in the current session?

sessionreqcount.jsp:

Example23
JCode Cell
1 
2<%
3Integer count=(Integer)application.getAttribute("usercount");
4if(session.isNew())
5{
6if(count==null)
7{
8count=1;
9}
10else
11{
12count++;
13}
14application.setAttribute("usercount",count);
15}
16%>
17<h1>The number of users login into our application:<%= count %></h1>
18

2) Programmatic Approach

  • Page Scope:

This scope is applicable only for JSPs but not for Servlets.

This scope is maintained by pageContext implicit object.

The information stored in Page Scope is available only in the current JSP and not available for

other JSPs.Hence it is most restricted scope.

Page Scope is the most commonly used scope in custom tags to share information between tag

handler classes.

PageContext class defines the following methods for attribute management in page scope.

Example24
JCode Cell
1 
2<%
3Integer count=(Integer)session.getAttribute("sessionreqcount");
4if(count==null)
5{
6count=1;
7}
8else
9{
10count++;
11}
12session.setAttribute("sessionreqcount",count);
13%>
14<h1>The number of requests in the current session: <%= count %> </h1>
15

2) Programmatic Approach

Extra methods of PageContext class to perform attribute management in any scope:

PageContext class defines the following methods to perform attribute management in any scope...

Example25
JCode Cell
1 
2public void setAttribute(String name,Object value)
3public void removeAttribute(String name)
4public Object getAttribute(String name)
5

2) Programmatic Approach

The allowed scopes are:

PageContext.PAGE_SCOPE 1

PageContext.REQUEST_SCOPE 2

PageContext.SESSION_SCOPE 3

PageContext.APPLICATION_SCOPE 4

Example26
JCode Cell
1 
2public void setAttribute(String name,Object value,int scope)
3

2) Programmatic Approach

Q.Which of the following is valid way to store an attribute in Page Scope?

Example27
JCode Cell
1 
2public Object getAttribute(String name,int scope)
3public void removeAttribute(String name,int scope)
4

2) Programmatic Approach

PageContext class defines the following extra methods also..

Example28
JCode Cell
1 
2page.setAttribute("durga","java");
3pageContext.setAttribute("durga","java");
4pageContext.setAttribute("durga","java",4);
5pageContext.setAttribute("durga","java",1);
6pageContext.setAttribute("durga","java",PageContext.PAGE_SCOPE);
7

2) Programmatic Approach

First it will searches in page scope and if the attribute present then returns its value. If it is not

available then it will search in request, session and then application scopes respectively.

This method acts as all rounder.

Q. What is the difference b/w getAttribute(String name) and findAttribute(String name)?

Q. What is the difference b/w getAttribute(String name) and getAttribute(String name,int scope)?

Example29
JCode Cell
1 
2public Enumeration getAttributeNamesInScope(int scope)
3public Object findAttribute(String name)
4

Demo Program to demonstrate JSP Scopes

Example30
JCode Cell
1 
2<%
3pageContext.setAttribute("p","page");
4request.setAttribute("r","request");
5session.setAttribute("s","session");
6application.setAttribute("a","application");
7pageContext.forward("second.jsp");
8%>second.jsp:
9Page Scope Attribute:<%= pageContext.getAttribute("p") %><br/>
10Request Scope Attribute:<%= pageContext.getAttribute("r",2) %><br/>
11Session Scope Attribute:<%= pageContext.getAttribute("s",3) %><br/>
12Application Scope Attribute:<%= pageContext.getAttribute("a",4) %>http://localhost:7777/jsp1/first.jsp
13

Demo Program to demonstrate findAttribute()method

There are 2 Types of syntaxes are possible to write JSPs.

Example31
JCode Cell
1 
2<%
3pageContext.setAttribute("a","page");
4request.setAttribute("a","request");
5session.setAttribute("a","session");
6application.setAttribute("a","application");
7%>
8<h1>Find Attribute value :<%= pageContext.findAttribute("a") %><h1>JSP Document
9

Demo Program to demonstrate findAttribute()method

If we are developing JSPs by using JSP Standard syntax, such type of JSPs are called JSP Pages.

If we are developing JSPs by using XML Based syntax, such type of JSPs are called JSP Documents.

Example32
JCode Cell
1 
2JSP Standard Syntax
3XML Based Syntax
4

4) Directives

In XML: <jsp:directive.page import="java.util.*" />

Example33
JCode Cell
1 
2<%@ page import="java.util.*" %>
3

4) Directives

In XML: <jsp:directive.include file="header.jsp" />

For the taglib directive there is no equivalent syntax in XML.We can provide equivalent syntax

indirectly by using <jsp:root> tag.

....

</jsp:root>

Example34
JCode Cell
1 
2<%@ include file="header.jsp" %>
3

7) Template Text

Example35
JCode Cell
1 
2Save the JSP File with .jspx extension
3Enclose total JSP in <jsp:root> tag.
4use <jsp-config> element in web.xml
5

7) Template Text

Note: From Servlet 2.4 Version onwards Web container can identify JSP Document automatically.

No special arrangement is required.

http://localhost:7777/jsp2/jspdoc1.jsp

Write a JSP Document to print hit count of the JSP.

Example36
JCode Cell
1 
2<web-app>
3<jsp-config>
4<jsp-property-group>
5<url-pattern>*.jspx</url-pattern>
6<jsp-xml>true</jsp-xml>
7</jsp-property-group>
8</jsp-config>
9</web-app>
10

JSP Page

Example37
JCode Cell
1 
2<%!
3int count=0;
4%>
5<%
6count++;
7%>
8

7) The Hit count is

Example38
JCode Cell
1 
2<%= count %>
3

JSP Document

Note:

It is not recommended to use both standard and xml based syntaxes simultaneously.

The main advantage of XML Based syntax is ,we can use xml editors like XML Spy for

writing and debugging JSPs very easily.

Note: In XML Based syntax all tags,attributes are case sensitive. Attribute values must be enclosed

either in single quotes or in double quotes.

Q. Which of the following is the valid way of importing java.util package in the JSP?

<jsp:page import="java.util.*" />

<jsp:directive page import="java.util.*" />

<jsp:page.directive import="java.util.*" />

<jsp:directive.page import="java.util.*" />

Example39
JCode Cell
1 
2<jsp:declaration> int count=0;</jsp:declaration>
3<jsp:scriptlet>count++; </jsp:scriptlet>
4<jsp:text> The Hit count is(XML Based):</jsp:text>
5<jsp:expression>count</jsp:expression>
6
📝 Key Takeaways
  • out is a JspWriter (buffered); pageContext is the gateway to all scopes
  • exception is only available on isErrorPage="true" pages
  • findAttribute() searches page, request, session, application in order