Skip to main content

JSP pageContext implicit object

When a JSP page is running you have up to “4 places”
where you can put objects to retrieve them later.

1) Page scope


What you put on your page scope is available only for the JSP page that put it.
Any other page in the same request included via or forwarded will not see object
in the first page scope.

This is the default scope,
so is the same to call

1
2
 
pageContext.setAttribute("a", "b", PageContext.PAGE_SCOPE);

than pageContext.setAttribute(“a”, “b”);

2) Request scope


What you put on your request scope is available across all the request serving this JSP page,
other pages included or forwarded (not HTTP redirect) will share this same context
and see these objects.

Is the same to call

1
2
 
pageContext.setAttribute("a", "b", PageContext.REQUEST_SCOPE);

than request.setAttribute(“a”, “b”);

3) Session scope


What you put on your session scope is available across all requests on the same user session.

Is the same to call

1
pageContext.setAttribute("a", "b", PageContext.SESSION_SCOPE);

than session.setAttribute(“a”, “b”);

4) Application scope


What you put on your application scope is available across all requests on
your application
(i.e. is shared by all users).

Is the same to call

1
2
 
pageContext.setAttribute("a", "b", PageContext.APPLICATION_SCOPE);

than application.setAttribute(“a”, “b”);

Let’s understand it with Example

Project Structure

pageContext.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
 
<%@ page language="java" %>
<html>
<head>
<title>Insert title here</title>
</head>
<body>
<%
pageContext.setAttribute("user","blakhani2012",pageContext.SESSION_SCOPE); 
 
%>
 
<a href="pageContext_Session.jsp">Click here to go to the welcome page</a>
</body>
</html>

pageContext_Session.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
 
<%@ page language="java"%>
<html>
<head>
<title>Insert title here</title>
</head>
<body>
<% 
 
String username=(String)pageContext.getAttribute("user",pageContext.SESSION_SCOPE);  
 
out.println("Hello "+username);
 
%>
</body>
</html>

output: