Struts2 ognl 标签详解
给出源码:
sortTag.jsp:
[java]
<%@ page language="java" contentType="text/html; charset=gb2312"
pageEncoding="gb2312"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<body>
<s:set name="frank" value="{'aefi','abc','world!','kkkkk'}" />
<s:bean id="sort" name="action.SortComparator"></s:bean>
<s:sort source="frank" comparator="sort">
<s:iterator>
<tr><td>
<s:property />
</td></tr>
</s:iterator>
</s:sort>
</body>
</html>
解析:
<s:bean id="sort" name="action.SortComparator"></s:bean>即,关联相关的java类文件(此为比较器类SortComparator)。其中id属性可看作就是SortComparator的一个实例。若不加入bean标签,则出现异常:javax.servlet.jsp.JspException: comparator [null] does not implements Comparator interface由下面的"sort标签官网释义",可知:sort标签中的comparator属性=比较器实例=bean的id属性值="sort"。
sort标签官网释义:
SortComparator.java:
[java]
package action;
import java.util.Comparator;
public class SortComparator implements Comparator<Object> {
public int compare(Object arg0, Object arg1) {
return arg0.toString().compareTo(arg1.toString());
}
}
在struts.xml中不用给出任何相关配置:
[html]
<?xml version="1.0" encoding="gb2312"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="struts.i18n.encoding" value="gb2312"/>
<package name="OGNLTAG" extends="struts-default">
</package>
</struts>