In this tutorial you will learn about the JSP PageContext Implicit Object and its application with practical example.
JSP PageContext Implicit Object
This is the instance of javax.servlet.jsp.PageContext object. The pageContext instance provides access to all namespace associated with JSP pages .
The PageContext class is an abstract class which defines some fields, including APPLICATION_SCOPE, SESSION_SCOPE, REQUEST_SCOPE,PAGE_SCOPE Which identify the four scope and also defines and inherit some methods like setAttribute, getAttribute,getPage,getRequest etc.
Example: Let’s get understand it with the help of simple example.First we need to create index.jsp file.
#index.jsp: From here we will fill text in textfields and will perform click action of button. Let’s do code for it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<%@page contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP Page</title> </head> <body> <pre> <form action="PageContext.jsp"> Name : <input type="text" name="uname"> Email : <input type="text" name="email"> <input type="submit" value="Click"><br/> </pre> </form> </body> </html> |
#Output: So the output of above code will look like below image, we have to click on “Click” button after filling data in text fields.
#PageContext.jsp: From here we will set our attributes like below code. Here we have set our attributes in PageContext.SESSION_SCOPE and we will get attributes from same SCOPE.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
<%@page contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP Page</title> </head> <body> <% String name = request.getParameter("uname"); String email=request.getParameter("email"); out.print("Welcome " + name+ " Email :"+email); pageContext.setAttribute("user",name,PageContext.SESSION_SCOPE); %> <a href = "pagecontext_second.jsp">Next Page</a> </body> </html> |
#Output: The output of above code will look like be below image.
#pagecontext_second.jsp: Here we will get attribute with the help of PageContext.SESSION_SCOPE, You can get understand it from below code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<%@page contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP Page</title> </head> <body> <% String name=(String)pageContext.getAttribute("user",PageContext.SESSION_SCOPE); out.print("Hello "+name); %> </body> </html> |
#Output: So finally we are done with all work of PageContext implicit object see below image which is output of above code.