自定义JSTL标签库(函数库)

jstl标签库的配置
 * 将jstl.jarstandard.jar拷贝到WEB-INF/lib下(如果使用el表达式,不用拷贝这两个jar)
 
 注意:jstl必须在能够支持j2ee1.4/servlet2.4/jsp2.0版本上的容器才能运行,这个环境
      是目前较为常用的环境

     
标签库的使用
 * 采用taglib指令引入
 <%@ taglib prefix="c"  uri="
http://java.sun.com/jsp/jstl/core"%
 <%@ taglib prefix="fmt" uri="
http://java.sun.com/jsp/jstl/fmt"%>
 
  
自定义函数库:
 1、定义类和方法(方法必须是public static) 
 2、编写自定义tld文件,并且将此文件放到WEB-INFWEB-INF任意子目录下
 3、在jsp中采用taglib指令引入自定义函数库
 4、采用 前缀+冒号(:)+函数名 调用即可
 

 

MyFunctions.java 

 

public class MyFunctions {
  
   public static String sayHello(String name) {
      return "Hello " + name;
   }
 
} 

   

myfunctions.tld

自定义标签

 



   
  my functions library
  my functions
  1.0
  my
  http://www.bjsxt.com/functions
 
  
    sayHello
    com.bjsxt.struts.MyFunctions
    java.lang.String sayHello(java.lang.String)
  
 

   

jstl_fn.jsp

 

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

prefix对应my
uri对应 http://www.bjsxt.com/functions

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

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

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

 

<%@ page language="java" import="java.util.*" pageEncoding="GB18030"%>
<%@ taglib uri="http://www.bjsxt.com/functions" prefix="my" %>

<%
request.setAttribute("name", "David");
%>



  
    testTemplate
  
  
    ${my:sayHello(name) }
  

  

 

补充:web-app version="2.4"

有时也需要在web.xml中添加对标签的定义:

 


    
        www.bjsxt.com/functions
        /WEB-INF/my.tld
    

 

 

注意:

  

可能出现的异常

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自带的标签元素冲突,重名等

 

你可能感兴趣的:(JSTL,JSP,Java,Web,SUN,XML)