在路上

 找回密码
 立即注册
在路上 站点首页 学习 查看内容

JSP自定义方法库

2016-12-20 13:12| 发布者: zhangjf| 查看: 446| 评论: 0

摘要: 如果JSTL的方法库没有满足需要,可以使用自定义方法进行扩展 public class Function{ public static int length(Object obj){ //返回对象的长度 if(obj == null){ ...

如果JSTL的方法库没有满足需要,可以使用自定义方法进行扩展

  1. public class Function{
  2. public static int length(Object obj){ //返回对象的长度
  3. if(obj == null){
  4. return 0;
  5. }
  6. if(obj instanceof StringBuffer){
  7. return lenth(((StringBuffer)obj).toString());
  8. }
  9. if(obj instanceof String){
  10. return ((String)obj).getBytes.length;
  11. }
  12. if(obj instanceof Collection){
  13. return ((Collection)obj).size();
  14. }
  15. }
  16. }
复制代码

配置文件
  1. <?xml version="1.0" ecoding="UTF-8">
  2. <taglib xmlns=http://java.sun.com/xml/ns/j2ee
  3. xmlns:xsi:="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation=http://java.sun.com/xml/ns/j2ee web-jsptaglibrary_2_0.xsd
  5. version="2.0">
  6. <description>custom functionslibrary</description>
  7. <display-name>customfunctions</display-name>
  8. <tlibversion>1.1</tlibversion>
  9. <shortname>function</shortname>
  10. <uri>http://www.clf.com/tags</uri>
  11. <function>
  12. <description>descriptioncontent </description>
  13. <name>lenth</name>
  14. <function-class>com.chen.Funtion</function-class>
  15. <function-signature>
  16. int length(java.lang.Object)
  17. </function-signature>
  18. <example>
  19. ${fn:length(string)}
  20. </example>
  21. <function>
  22. </taglib>
复制代码

自定义方法的声明写在 标记里面,格式为

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

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

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

${fn:length(string)}

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


最新评论

小黑屋|在路上 ( 蜀ICP备15035742号-1 

;

GMT+8, 2025-7-8 03:46

Copyright 2015-2025 djqfx

返回顶部