检查 JSP 中是否存在属性
我有一些扩展超类的类,并且在 JSP 中我想显示这些类的一些属性。我只想制作一个JSP,但我事先不知道该对象是否有属性。所以我需要一个 JSTL 表达式或一个标签来检查我传递的对象是否具有此属性(类似于 javascript 中的 in 运算符,但在服务器中)。
<c:if test="${an expression which checks if myAttribute exists in myObject}">
<!-- Display this only when myObject has the atttribute "myAttribute" -->
<!-- Now I can access safely to "myAttribute" -->
${myObject.myAttribute}
</C:if>
我怎样才能得到这个?
谢谢。
I have some classes which extends a superclass, and in the JSP I want to show some attributes of these classes. I only want to make one JSP, but I don't know in advance if the object has an attribute or not. So I need a JSTL expression or a tag which checks that the object I pass has this attribute (similar to in operator in javascript, but in the server).
<c:if test="${an expression which checks if myAttribute exists in myObject}">
<!-- Display this only when myObject has the atttribute "myAttribute" -->
<!-- Now I can access safely to "myAttribute" -->
${myObject.myAttribute}
</C:if>
How can I get this?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
使用 JSTL
c:catch< /代码>
。
Make use of JSTL
c:catch
.您可以轻松创建自定义函数来检查属性,按照 vivin 的博客文章。
简而言之,如果您已经拥有自己的 taglib,那么只需创建一个静态“hasProperty”方法...
...并向您的 TLD 添加五行...
...并在 JSP 中调用它
You can readily create a custom function to check for the property, as per vivin's blog post.
In short, if you already have your own taglib its just a matter of creating a static 'hasProperty' method...
...and adding five lines to your TLD...
... and calling it in your JSP
当我只想测试对象是否有字段但不想输出字段的值时,接受的答案可能会产生一些副作用。在上述情况下,我使用下面的代码片段:
希望这会有所帮助。
The accepted answer may have some side effects when I just want to test if the object has a field, but do not want to output the value of the field. In the mentioned case, I use the snippet below:
hope this helps.
只是 BalusC 伟大答案的更详细(典型?)用法
正如 Shervin 在 BalusC 答案的评论中指出的那样,这可能不是最干净的解决方案,但正如 BalusC 回答的那样“这是迄今为止实现奇怪要求的唯一方法” 。
资源
Just a more detailed (typical?) usage of BalusC great answer
As pointed out by Shervin in the comments of BalusC's answer, this is probably NOT the cleanest solution but as replied by BalusC "that's so far the only way to achieve the odd requirement".
Resources
你的意思是这样的:
或其他变体
如果它是一个列表你可以做
Do you mean something like this:
or other variant
If it is a list you can do