Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
517 views
in Technique[技术] by (71.8m points)

java - I can pass a variable from a JSP scriptlet to JSTL but not from JSTL to a JSP scriptlet without an error

The following code causes an error:

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

The error says

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

How do I pass test from the JSTL code to the JSP scriptlet?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

In contrast, JSTL works entirely with scoped attributes, either at page, request or session scope. You need to rework your scriptlet to fish test out 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'll see you can specify scope as page, request or session, and it defaults to page.

Better yet, don't use scriptlets at all: they make the baby jesus cry.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

62 comments

56.5k users

...