I have this on welcome.jsp
<c:set var="pgTitle" value="Welcome"/> <jsp:include page="/jsp/inc/head.jsp" />
And this in head.jsp:
<title>Site Name - ${pgTitle}</title>
But the variable is blank, and the output is merely
Site Name -
I have read many articles, and I cannot figure out what the problem is. If I echo ${pgTitle}
elsewhere within the same welcome.jsp, then it outputs fine.
I am including the core tag library on both pages.
Scope decides the accessibility of an object or variable. For example, some variables are accessible within for loop, if-else block or within specific method or class or package. Advertisements. Same way, in JSP some variables needs to have different scopes than others.
c:set allows to set the result of an expression in a variable within a given scope. Using this tag helps to set the property of 'JavaBean' and the values of the 'java. util. Map' object.
The availability of a JSP object for use from a particular place of the application is defined as the scope of that JSP object. Every object created in a JSP page will have a scope. Object scope in JSP is segregated into four parts and they are page, request, session and application.
This is because the pgTitle
variable is set in page scope. Check it here(sorry I can't get an official documentation for this).
If you want to make this work, you have to set the variable in request scope at least. To set your variable in request scope, use the scope
attribute on <c:set>
:
<c:set var="pgTitle" value="Welcome" scope="request" />
Per your comment, in web development, the scope of the variables matter because it defines where the variable can be used (similar to a variable declared as field in a class and a variable declared locally in a method). There are four scopes in JSP known as context:
More info:
Is this the right way to accomplish what I am trying to do?
If there's a Servlet or another controller that handles the attributes to be set in the request (e.g. @Controller
from Spring MVC or JSF managed bean), then set the attribute there and not in your page directly.
Personally, it takes some time to earn experience and define the best scope of the variables when used on web applications. Basic examples:
String
by comma for presentation purposes will affect only to current view, so this can be set in page scope.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With