Velocity中如何判断null
遇到一个棘手问题,用velocity得到从action传过来的String值(里面的内容用", "隔开),把此String值split后得到数组,虽然可以遍历此数组,但是不能得到此数组的长度。
#set($two = ${question.questionTwo.split(", ")})
#foreach($c in $two)
$!{c}
#end
<pre name="code" class="html">$!{two.length()}
#end
c可以遍历出来,但是数组的长度得不到。而且浏览器加载缓慢,刷新多次才出现。这是利用velocity的问题。所以,尽量让velocity少得有业务逻辑,把逻辑写在后台。
经过潘云飞调试。改动如下:
在Question.java中新增此方法
public List<String> getQuestionTwoList(){
List<String> certification = new ArrayList<String>();
if(this.questionTwo != null&& !"".equals(questionTwo)){
String [] a = questionTwo.split(", ");
for(int i=0; i<a.length; i++){
certification.add(a[i]);
}
return certification;
}else{
return null;
}
}
谢了此方法后,questionTwoList可以当做属性读取,这个以后得研究一下。
</pre>把questionTwo内的值转为List,把List传出来。<p></p><p>前台questions.html改动如下:</p><p></p><pre name="code" class="html">#if(!${question.questionTwo})
<span>同问 0</span>
#else
#set($two = ${question.questionTwoList})
<span>同问 $two.size() </span>
#end