Difference between jsp:useBean and c:set – pageContext and scripting variable scopes

I always get confused about the pageContext scope and scripting variable scope. Here is a code that illustrates the difference between jsp:useBean and c:set. It also shows difference between pagecontext variable and scripting variable.

<%–
Document   : index
Created on : Sep 5, 2008, 11:12:06 AM
Author     : gundlapa
–%>

<%@page contentType=”text/html” pageEncoding=”UTF-8″%>
<%@ taglib uri=”http://java.sun.com/jsp/jstl/core&#8221; prefix=”c”%>
<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN”
http://www.w3.org/TR/html4/loose.dtd”&gt;

<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″>
<title>JSP Page</title>
</head>
<body>
<jsp:useBean id=”myVar” class=”java.util.Date”/>
Scripting variable value using expression: <%=myVar%><BR>
Variable value using C:Out <c:out value=”${myVar}”/><BR>
<c:set var=”myVar” value=”Today”/><BR>
<B>The values after changing myVar using c:set</B><BR><BR>
Scripting variable value using expression: <%=myVar%><BR>
Variable value using C:Out <c:out value=”${myVar}”/><BR><BR>
Printing the value of myVar in pageContext:<%= pageContext.getAttribute(“myVar”)%>

</body>
</html>

Here is the output of the JSP:

Scripting variable value using expression: Fri Sep 12 14:19:18 CDT 2008
Variable value using C:Out Fri Sep 12 14:19:18 CDT 2008

The values after changing myVar using c:set

Scripting variable value using expression: Fri Sep 12 14:19:18 CDT 2008
Variable value using C:Out Today

Printing the value of myVar in pageContext:Today

Advertisements

2 Responses to Difference between jsp:useBean and c:set – pageContext and scripting variable scopes

  1. Pingback: JSTL true and ‘true’ comparisions and the scope where JSTL looks for variable « Suneel Gundlapalli’s blog

  2. suneelgv says:

    Note: As a site effect, jsp:useBean also generates a scripting variable besides setting the variable in the specified scope. This scripting variable can be used in jsp scriptlets and expression. I always keep forgetting this for some reason!!!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: