如果JSTL的方法库没有满足需要,可以使用自定义方法进行扩展 - public class Function{
- public static int length(Object obj){ //返回对象的长度
- if(obj == null){
- return 0;
- }
-
- if(obj instanceof StringBuffer){
- return lenth(((StringBuffer)obj).toString());
- }
-
- if(obj instanceof String){
- return ((String)obj).getBytes.length;
- }
-
- if(obj instanceof Collection){
- return ((Collection)obj).size();
- }
- }
- }
复制代码
配置文件- <?xml version="1.0" ecoding="UTF-8">
-
- <taglib xmlns=http://java.sun.com/xml/ns/j2ee
- xmlns:xsi:="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation=http://java.sun.com/xml/ns/j2ee web-jsptaglibrary_2_0.xsd
- version="2.0">
-
- <description>custom functionslibrary</description>
- <display-name>customfunctions</display-name>
- <tlibversion>1.1</tlibversion>
- <shortname>function</shortname>
- <uri>http://www.clf.com/tags</uri>
-
-
- <function>
- <description>descriptioncontent </description>
- <name>lenth</name>
- <function-class>com.chen.Funtion</function-class>
- <function-signature>
- int length(java.lang.Object)
- </function-signature>
- <example>
- ${fn:length(string)}
- </example>
- <function>
-
- </taglib>
复制代码
自定义方法的声明写在 标记里面,格式为
返回值 方法名(参数1类型,参数2类型……)
加入有个String型变量,赋值“字符串测试”
在JSP页面中定义的标签库的前缀是“fn”,则用法如下
${fn:length(string)}
这句话就能输出字符串的长度
|