Master java skills

pageContext Implicit Object

pageContext implicit object is used to get, set or remove attributes from one of the following scopes:

  1. page
  2. request
  3. session
  4. application

Note -> Default scope of pageContext is page

pageContext is implicit object of PageContext class.

PageContext Example

For this example, we have to add jsp-api maven dependency. Please find the complete pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.sks</groupId>
	<artifactId>my-first-jsp-app</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<dependencies>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>4.0.1</version>
			<scope>provided</scope>
		</dependency>

		<!-- https://mvnrepository.com/artifact/javax.servlet/jsp-api -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jsp-api</artifactId>
			<version>2.0</version>
			<scope>provided</scope>
		</dependency>

	</dependencies>

</project>

index.html

<html>  
  <body>  
    <form action="welcome.jsp">  
      Username : <input type="text" name="username"><br>  
      <input type="submit" value="Submit">
    </form>  
  </body>  
</html>  

welcome.jsp

<html>
	<body>
		<%   
			String name=request.getParameter("username");  
			out.print("Welcome " + name + "<br>");  
			pageContext.setAttribute("user", name, PageContext.SESSION_SCOPE);  
		%>
			<a href="pageContext.jsp">Test Page Context Value</a>
	</body>
</html>

pageContext.jsp

<html>
  <body>
	<%   
      String username = (String)pageContext.getAttribute("user",PageContext.SESSION_SCOPE);  
      out.print("Hello " + username);  
    %>
  </body>
</html>

Run and test