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

Categories

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

java - Struts2 s:if test for non-null value

I am wanting to test for a non-null value using a struts2 tag. This works if I use the following:

<s:if test="myObject.myField != null">..stuff..</s:if>

It also seems to work if I miss out the not-null part, and just do:

<s:if test="myObject.myField">..stuff..</s:if>

However, when myField is a String, this no longer works. I prefer the second form as it is more concise, and seems less like putting code in my presentation layer. But I don't want to use it if it's an undocumented feature which is somehow working by accident, as suggested by the fact that it doesn't work for strings.

So my question is, is it ever ok to miss out "!= null" in the above test?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Using <s:if test="whatsoever the whatsoever is an OGNL expression that should evaluate to Boolean value if you want the tag is working right. If your field is of boolean type it's ok, in other case it's just doesn't work.

Also, in the documentation page for the if tag the type is defined as Boolean, so it's not primitive boolean but the value could be primitive boolean. So, be careful when using different types when evaluating the test case.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...