现在的位置: 首页 > 综合 > 正文

logic:present 和 logic:empty标签

2012年02月20日 ⁄ 综合 ⁄ 共 1288字 ⁄ 字号 评论关闭
 

logic:present 和 logic:empty他们的用法大致相同,唯一的不同点是:两者在对空字符串的处理上存在着不同。

下面为index.jsp中的代码:

1
<logic:notPresent name="users">
2  notpresent
3</logic:notPresent>
4<logic:notEmpty name="users">
5  notempty
6</logic:notEmpty>
7<logic:empty name="users">
8  empty
9</logic:empty>
10<logic:present name="users">
11  present
12</logic:present>

当第一次访问该JSP的时候,由于users没有定义,并且也不在page,request,session,application任何一个作用域中,因此输出的结果为notpresent,empty。

下面我们增加一个action,让他在index.jsp之前执行,然后再跳转到index.jsp中,同时在该action的execute方法中增加如下代码:
 

1String userName
= "";
2request.setAttribute("users",
userName);
3return
new ActionForward("/index.jsp");
4

这里将userName保存在request中,key为users,再将请求转发至index.jsp中,但是userName的值为一个空字符串,转发过后,输出的值为:empty,present

这里我们再做一次改动,将action的execute方法中的代码改为:

1String userName
= null;
2request.setAttribute("users",
userName);
3return
new ActionForward("/hello.jsp");
4

不同的是userName 不再为空字符串了,而是null值,当转发至index.jsp后,输出的值为:notpresent,empty 。

对比这几次改动,我们可以得出结论:

对于没有在page,request,session,application中定义或者是没有分配内存空间(null值)的变量,这两个标记处理的方法是一致的,都会认为此变量不存在(notpresent)或者为空(empty)。而对于空字符串""值,他们的处理就不一样了,logic:present 标记认为空字符串仍然是存在的,也就是说,只要是引用了一块内存空间的变量,logic:present 就会返回present ;而logic:empty则认为空字符串仍然为空,由此得出,在logic:empty看来,变量不仅仅要引用一块内存空间,而且该地址空间的值不能为空字符串,否则都认为该变量为空,都会返回empty

抱歉!评论已关闭.