`
午刀十
  • 浏览: 34143 次
  • 性别: Icon_minigender_1
  • 来自: 厦门
社区版块
存档分类
最新评论

自定义JSTL

阅读更多
      自己定义JSTL标签函数,可以大大简化我们在开发中的工作。我们可以定义自己需要的函数,使用也极其方便。
以下通过显示重要等级来看实现步骤:
首先,要新建一个JAVA类,提供方法: TagFunction.java
 package myUtil;    
	import java.util.ArrayList;  
	import java.util.List;  
	// 自定义JSTL函数  
	public class TagFunction {  
	    // 获取重要等级  
         public static List getImportantLevel () {  
	        List importantLevel = new ArrayList();  	          
	        importantLevel .add("全部");  
	        importantLevel .add("重要");  
	        importantLevel .add("一般");  
	        importantLevel .add("低");  	          
	        return importantLevel ;     
	    }     
	}  

其次,要编写tld标签函数注册文件,将之前写的java 类方法注册到tld:tagfunctions.tld
	<?xml version="1.0" encoding="gb2312" ?>  
	  
	<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">  	      
	  <tlib-version>1.0</tlib-version>  
	  <short-name>myTag</short-name>  
	  <uri>myTag</uri>  
	    
	  <!-- JSTL自定义函数  获取重要等级 -->  
	  <function>  
	    <name>getImportantLevel</name>  
	    <function-class>myUtil.TagFunction</function-class>  
	    <function-signature>java.util.List getImportantLevel()</function-signature>  
	  </function>  
	</taglib> 

接着还要在web.xml文件中注册刚才创建的tld :
1.	<?xml version="1.0" encoding="UTF-8"?>  
2.	<web-app version="2.5"   
3.	    xmlns="http://java.sun.com/xml/ns/javaee"   
4.	    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
5.	    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   
6.	    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">  
7.	  <welcome-file-list>  
8.	    <welcome-file>index.jsp</welcome-file>  
9.	  </welcome-file-list>  
10.	    
11.	  <!—我们添加的代码,注册JSTL函数 -->  
12.	  <jsp-config>  
13.	    <taglib>  
14.	        <taglib-uri>myTag</taglib-uri>  
15.	        <taglib-location>/WEB-INF/tagfunctions.tld</taglib-location>  
16.	    </taglib>  
17.	  </jsp-config>  
18.	    
19.	</web-app> 

然后我们就可以编写jsp进行测试了 :index.jsp
	<%@ page language="java" import="java.util.*" pageEncoding="gbk"%>  
	<!-- 导入jstl标签库 -->  
	<%@ taglib prefix="c"  uri="http://java.sun.com/jsp/jstl/core" %>  
	<!-- 导入我们自己定义的jstl函数 -->  
	<%@ taglib prefix="myTag " uri="myTag"%>  
	  
	<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
	<html>  
	  <head>  
	    <title>自定义JSTL函数</title>  
	  </head>  
	    
	  <body>  
	    重要等级:  
	    <select name="importantLevel">  
	    <option>--请选择重要等级--</option>  
	    <c:forEach items="${ myTag:getImportantLevel()}" var="t">  
	        <option>${t}</option>  
	    </c:forEach>  
	    </select>  
	  </body>  
	</html> 

最后,只要把例子部署到tomcat测试就可以了,结果正确显示重要等级下拉框。
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics