自定义jstl标签库

自定义函数库:
 1、定义类和方法(方法必须是public static) 
 2、编写自定义tld文件,并且将此文件放到WEB-INFWEB-INF任意子目录下
 3、在jsp中采用taglib指令引入自定义函数库
 4、采用 前缀+冒号(:)+函数名 调用即可 

MyFunctions.java 

代码:

[java] view plain copy
 
  1. public class MyFunctions {     
  2.        
  3.    public static String sayHello(String name) {     
  4.       return "Hello " + name;     
  5.    }     
  6.       
  7. }     

myfunctions.tld

自定义标签

xml代码:

[xhtml] view plain copy
 
  1. <?xml version="1.0" encoding="UTF-8" ?>    
  2.     
  3. <taglib xmlns="http://java.sun.com/xml/ns/j2ee"    
  4.   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    
  5.   xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"    
  6.   version="2.0">    
  7.         
  8.   <description>my functions library</description>    
  9.   <display-name>my functions</display-name>    
  10.   <tlib-version>1.0</tlib-version>    
  11.   <short-name>my</short-name>    
  12.   <uri>http://www.bjsxt.com/functions</uri>    
  13.       
  14.   <function>    
  15.     <name>sayHello</name>    
  16.     <function-class>com.bjsxt.struts.MyFunctions</function-class>    
  17.     <function-signature>java.lang.String sayHello(java.lang.String)</function-signature>    
  18.   </function>    
  19.       
  20. </taglib>    

jstl_fn.jsp

注意与前面的配置文件myfunctions.tld相对应,

prefix对应<short-name>my</short-name>
uri对应 <uri>http://www.bjsxt.com/functions</uri>

可使用以下面两种方式给name赋值:

1、${my:sayHello("David") }

2、request.setAttribute("name", "David");

代码:

[java] view plain copy
 
  1. <%@ page language="java" import="java.util.*" pageEncoding="GB18030"%>     
  2. <%@ taglib uri="http://www.bjsxt.com/functions" prefix="my" %>     
  3.     
  4. <%     
  5. request.setAttribute("name", "David");     
  6. %>     
  7.     
  8. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">     
  9. <html>     
  10.   <head>     
  11.     <title>testTemplate</title>     
  12.   </head>     
  13.   <body>     
  14.     ${my:sayHello(name) }     
  15.   </body>     
  16. </html>    

最后:

还需要在web.xml中注册:

eg:

[java] view plain copy
 
  1. <jsp-config>    
  2.     <taglib>    
  3.         <taglib-uri>www.bjsxt.com/functions</taglib-uri>    
  4.         <taglib-location>/WEB-INF/my.tld</taglib-location>    
  5.     </taglib>    
  6. </jsp-config>    

注:要引用的时候,在web.xml文件中配置的那个uri的地址就是我们要引进时的那个uri  

注意:

  

可能出现的异常

1、The function xxx must be used with a prefix when a default namespace is not specified

--- 在jsp页面中调用方式不正确,可能将 ":" 写成了 "."

2、The function xxx cannot be located with the specified prefix

--- a) 类中定义的方法不是 public static 的方法

      b) 类中的方法名称和jsp自带的标签元素冲突,重名等

原文地址:https://www.cnblogs.com/cnsdhzzl/p/5601247.html