现在的位置: 首页 > 综合 > 正文

EL表达式—自定义函数(转)

2012年08月06日 ⁄ 综合 ⁄ 共 1286字 ⁄ 字号 评论关闭

有看到一个有趣的应用了,转下来,呵呵!!

1.定义类MyFunction(注意:方法必须为 public static)

package com.tgb.jstl;  
  
  
/** 
 
 * JSTL标签中的自定义函数库实现类 
  
 * 
 
 
*/  
  
public class MyFunctions {  
  
    public static String sayHello(String name){  
  
      return  "Hello  " + name;  
  
    }  
  
}  

2.提供tld描述文件,此文件可以放到WEB-INF下或其目录下.

<?xml version="1.0" encoding="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 http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"  
  version
="2.0">  
  <description>myFunctions library</description>  
  <display-name>JSTL functions</display-name>  
  <tlib-version>1.1</tlib-version>  
  
  <!--这里的所谓“简称”,可以随便写-->  
  <short-name>mfn</short-name>  
  <!--这里的uri,可以随便写-->  
  <uri>http://www.tgb.com/functions</uri>  
  
   <function>  
    <!--这里name可以随便写-->  
    <name>say</name>  
    <!--这里最为重要,指定类所在位置,以及类方法的一些重要信息-->  
    <function-class>com.tgb.jstl.MyFunctions</function-class>  
    <function-signature>java.lang.String  sayHello(java.lang.String)</function-signature>  
  </function>  
  
  </taglib>  

3.jsp页面中采用taglib引入函数库

<%@ taglib uri="http://www.tgb.com/functions" prefix="mfn" %> 

 

 4.el表达式中采用前缀+冒号+函数名称使用

  调用函数库相关函数,需要配合el表达式来使用。

${mfn:say("Tom") } <<---"Tom"可改为从EL表达式中取值

抱歉!评论已关闭.