I can pass a variable from JSP script to JSTL, but not from JSTL to JSP script without error

The following code throws an error:

1. <c:set var="test" value="test1"/> 2. <% 3. String resp = "abc"; 4. resp = resp + test; 5. pageContext.setAttribute("resp", resp); 6. %> 7. <c:out value="${resp}"/> 

Error says

 "error a line 4: unknown symbol 'test'". 

How to pass test from JSTL code to JSP script?

+44
java scope jsp scriptlet jstl
Aug 25 '10 at 21:06
source share
2 answers

Scripts are raw java embedded in the page code, and if you declare variables in your scripts, they become local variables embedded in the page.

In contrast, JSTL works completely with cloud attributes, either in the page , request , or session . You need to redo your scriptlet to catch test as an attribute:

 <c:set var="test" value="test1"/> <% String resp = "abc"; String test = pageContext.getAttribute("test"); resp = resp + test; pageContext.setAttribute("resp", resp); %> <c:out value="${resp}"/> 

If you look at the docs for <c:set> , you will see that you can specify scope as page , request or session , and default is page .

Better yet, don't use scriptlets at all: they make your child sigh.

+97
Aug 25 '10 at 21:11
source share

@skaffman nailed it. They live each in their own context. However, I would not consider scripts as a solution. You want to avoid them. If you only want to concatenate lines in EL, and you find that the + operator fails for lines in EL (this is correct), simply do:

 <c:out value="abc${test}" /> 

Or, if abc must be obtained from another variable called ${resp} , then do:

 <c:out value="${resp}${test}" /> 
+13
Aug 25 '10 at 21:16
source share



All Articles