Java 如何使用 EL + JSTL 将任意对象转换为字符串?(调用 toString())
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2883726/
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
How to convert an arbitrary object to String with EL + JSTL? (calling toString())
提问by Hans-Peter St?rr
Is there any way to call toString() on an object with the EL and JSTL? (I need the String representation of an enum as index in a map in a JSP EL expression.) I hoped something like ${''+object}
would work like in java, but EL isn't that nice, and there does not seem to be any function that does it.
有什么方法可以使用 EL 和 JSTL 在对象上调用 toString() 吗?(我需要枚举的字符串表示作为 JSP EL 表达式中映射中的索引。)我希望类似的东西${''+object}
可以像在 Java 中一样工作,但 EL 不是那么好,而且似乎没有任何函数可以它。
Clarification: I have a variable somemap
that maps Strings to Strings, and I have a variable someenum
that is an enumeration. I'd like to do something like ${somemap[someenum.toString()]}
. (Of course .toString() does not work, but what does?)
说明:我有一个somemap
将字符串映射到字符串的变量someenum
,我有一个枚举变量。我想做类似的事情${somemap[someenum.toString()]}
。(当然 .toString() 不起作用,但什么起作用?)
采纳答案by skaffman
You just do it like this:
你只需这样做:
${object}
And it'll toString
it for you.
它会toString
为你。
edit: Your nested expression can be resolved like this:
编辑:您的嵌套表达式可以这样解析:
<c:set var="myValue">${someenum}</c:set>
${somemap[myValue]}
The first line stringifies (using toString()
) the ${someenum}
expression and stores it in the myValue
variable. The second line uses myValue
to index the map.
第一行字符串化(使用toString()
)${someenum}
表达式并将其存储在myValue
变量中。第二行用于myValue
索引地图。
回答by Will Hartung
Couple things you can do.
你可以做几件事。
One, you can use c:set -
一,你可以使用 c:set -
<c:set var="nowAString">${yourVar}</c:set>
Another thing you can do is create your own EL function, call it toString, and then call that in JSTL. EL functions are basically static methods hooked up with a taglib file. Straightforward to do.
您可以做的另一件事是创建您自己的 EL 函数,将其调用为 toString,然后在 JSTL 中调用它。EL 函数基本上是与 taglib 文件挂钩的静态方法。直截了当。
Edit:
编辑:
Really? Did you actually, you know, try it?
真的吗?你真的,你知道,尝试过吗?
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%@taglib uri="http://java.sun.com/jstl/core" prefix="c" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Hello World!</h1>
<%
pageContext.setAttribute("testDate", new java.util.Date());
%>
<c:set var="myVar">${testDate}</c:set>
testDate = ${testDate}<br/>
myVar = ${myVar}<br/>
testDate Class = ${testDate.class}<br/>
myVar Class = ${myVar.class}<br/>
</body>
</html>
And JSP 2.0 tagfile and JSTL functions are trivial.
并且 JSP 2.0 标记文件和 JSTL 函数是微不足道的。
回答by BalusC
The answer of Will Hartung should work. Here's a copy'n'paste'n'runnable SSCCE:
Will Hartung 的回答应该有效。这是一个 copy'n'paste'n'runnable SSCCE:
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!doctype html>
<%!
enum MyEnum {
FOO, BAR
}
%>
<%
request.setAttribute("myEnum", MyEnum.FOO);
java.util.Map<String, String> map = new java.util.HashMap<String, String>();
map.put("FOO", "value of key FOO");
map.put("BAR", "value of key BAR");
request.setAttribute("map", map);
%>
<html lang="en">
<head>
<title>Test</title>
</head>
<body>
<p>Map: ${map}
<p>Enum: ${myEnum}
<c:set var="myEnumAsString">${myEnum}</c:set>
<p>Map value: ${map[myEnumAsString]}
</body>
</html>
This yields:
这产生:
Map: {BAR=value of key BAR, FOO=value of key FOO}
Enum: FOO
Map value: value of key FOO
映射:{BAR=键 BAR 的值,FOO=键 FOO 的值}
枚举:FOO
映射值:键 FOO 的值
(scriptlets are just for quick prototyping, don't use them in real!)
(scriptlet 仅用于快速原型设计,请勿在实际中使用它们!)
回答by Sebastien Lorber
I think in new versions of JSP api you can call methods, even with parameters!
我认为在新版本的 JSP api 中,您可以调用方法,甚至可以使用参数!
I just tried ${statusColorMap[jobExecution.exitStatus.toString()]}
and it works fine!
我刚试过${statusColorMap[jobExecution.exitStatus.toString()]}
,效果很好!
回答by AechoLiu
//In java
public class Foo {
// Define properties and get/set methods
private int prop1;
private String prop2;
public String toString() {
String jsonString = ...; /// Convert this object to JSON string
return jsonString;
}
}
As skaffman said, EL syntax ${obj}
will call toString()
.
正如skaffman 所说,EL 语法${obj}
将调用toString()
.
So, if a object foo
in JSTL
is an instance of Foo
.
Then,
因此,如果对象foo
inJSTL
是Foo
. 然后,
// test.jsp
<script>
var a = ${foo}; // ${foo} will be {"prop1": ooo, "prop2": "xxx"}
console.log(a.prop1);
console.log(a.prop2);
</script>
Example
例子
If toString()
will output JSON
format string, for example, Foo
's toString()
outputs JSON
format string. then:
iftoString()
将输出JSON
格式字符串,例如Foo
'stoString()
输出JSON
格式字符串。然后:
// .java codes
Foo a = ...// a Foo object. => { 'prop1': ooo }
List<Foo> b = ... //< Array. => [ {'prop1': ooo}, {prop1: xxx} ]
// Pass object to JSTL by HttpServletRequest or ..
request.setAttribute('a', a);
request.setAttribute('b', b);
// .jsp codes
<span>${a.prop1}</span>
<script>
var aa = ${a}; // ${a} => { 'prop1': ooo }
var bb = ${b}; // ${b} => [ {'prop1': ooo}, {prop1: xxx} ]
console.log(aa.prop1);
console.log(bb[0].prop1);
</script>
回答by William Leung
ugly but simple enough
丑陋但足够简单
<someTag someValue="${yourObject}${''}" ... />
for example, someValue only accept strings (but declare as java.lang.Object), this way enforce it with string concatenation
例如,someValue 只接受字符串(但声明为 java.lang.Object),这种方式通过字符串连接来强制它