JSP自定义方法库

如果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>

 

自定义方法的声明写在 <function-signature>标记里面,格式为

      返回值 方法名(参数1类型,参数2类型……)

 

加入有个String型变量,赋值“字符串测试”

在JSP页面中定义的标签库的前缀是“fn”,则用法如下

                    ${fn:length(string)}

这句话就能输出字符串的长度


  • 6
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值