Java 在 JSP 中,是否可以打印名称在另一个变量中的变量的值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1311260/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 08:06:07  来源:igfitidea点击:

Is it possible, In JSP, to print the value of a variable whose name is in another variable?

javajspjakarta-ee

提问by Rakesh Juyal

The problem i am having is like this there is variable

我遇到的问题是这样的有变量

<core:set var="type">*one of: load,migrate, or ...* </core:set>

and the value of load, migrate,is a map. Now, i want to print the value of these based on the type? Is it possible at all?

load 和 migrate的值是一个映射。现在,我想根据类型打印这些值?有可能吗?

采纳答案by Nick Holt

This will achieve the same effect as @Chii's answer:

这将达到与@Chii 的回答相同的效果:

<c:set var="attributeName" value="foo"/>

<%
  out.println(pageContext.getAttribute(attributeName) + " = " + pageContext.getAttribute(pageContext.getAttribute(attributeName)));
%>

This, nasty as it is, will list all the attributes in the page scopeif you need to do that:

这虽然很糟糕,但如果您需要这样做,它将列出页面范围内的所有属性:

<%
  for (String attributeName : pageContext.getAttributeNamesInScope(PageContext.PAGE_SCOPE))
  {
    out.println(attributeName + " = " + pageContext.getAttribute(attributeName));
  }
%>

Don't think there's a way to do this in JSTL, but you normally only need this during debugging so I don't have such a problem with the scriptlet code.

不要认为在 JSTL 中有一种方法可以做到这一点,但您通常只在调试期间需要它,所以我对 scriptlet 代码没有这样的问题。

回答by Chii

if they are not in a map, its hard.

如果他们不在地图上,那就很难了。

I assume you wanted to do it the way perl works: where you could type

我假设您想按照 perl 的工作方式进行操作:您可以输入的位置

$foo = "stuff";
$varName = "foo";
print $$varName; #prints "stuff"

That doesnt work in jsp.

这在jsp中不起作用。

If its a map,you can do ${mapValue[key]}. Info on this pagenear the Variables section

如果是地图,你可以做${mapValue[key]}。信息在此页附近变量部分