JSP implicit object "pageContext"

The pageContext object is an instance of a JSP API javax.servlet.jsp.PageContext abstract class. It provides useful context information. That is it provides methods to get and set attributes in different scopes and for transferring requests to other resources. Also it contains the reference to to implicit objects.
The PageContext abstract class defines several fields, including PAGE_SCOPE, REQUEST_SCOPE, SESSION_SCOPE, and APPLICATION_SCOPE, which identify the four scopes.
The PageContext class provides methods that are used to create other objects. For example, its getOut method returns a JspWriter object that is used to send strings to the web browser. Other methods that return servlet-related objects include the following:
  • getRequest, returns a ServletRequest object
  • getResponse, returns a ServletResponse object
  • getServletConfig, returns a ServletConfig object
  • getServletContext, returns a ServletContext object
  • getSession, returns an HttpSession object
Example of implict object "pageContext" :
<html> <head> <title>welcome implict object pageContext example </title> </head> <body> <form action="welcome" method="post"> User Name <input type="text" name="user"> &nbsp; <input type="submit" value="Submit"> <br> </form> </body> </html>
<%@ page language="java" %> <html> <head> <title>index page</title> </head> <body> <% String name=request.getParameter("user"); out.println("hi "+name ); out.println("<BR>"); ServletContext context=pageContext.getServletContext(); //using page context to get context param value String web_name=context.getInitParameter("website"); out.println(web_name); pageContext.setAttribute("user", name,pageContext.SESSION_SCOPE); %> <a href="welcome.jsp">welcome page </a> </body> </html>
<%@ page language="java"%> <html> <head> <title>welcome page </title> </head> <body> <% String user=(String)pageContext.getAttribute( "user",pageContext.SESSION_SCOPE); out.println("Welcome page context user " +user); %> </body> </html>
<?xml version="1.0" encoding="UTF-8"?> <web-app> <display-name>pageContextExample</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> </welcome-file-list> <context-param> <param-name>website</param-name> <param-value>www.nsstudent.com</param-value> </context-param> <servlet> <servlet-name>welcome</servlet-name> <jsp-file>/index.jsp</jsp-file> </servlet> <servlet-mapping> <servlet-name>welcome</servlet-name> <url-pattern>/welcome</url-pattern> </servlet-mapping> </web-app>
Download this example


Latest Tutorial

Most Visited Tutorial