使用自定义tld标签简化jsp的繁琐操作

时间:2023-03-09 21:19:17
使用自定义tld标签简化jsp的繁琐操作

  最近做一个树形结构的展示,请求目标页面后,后台只返回简单的List,虽然有想过在jsp页面内做一些操作简化,但是太繁琐了,其他的标签又不能满足需求,所以只能自己做一个。使用tld标签可以简化jsp代码,以后也可以重用代码,所以出于这两个优点,用自定义的tld标签是一个不错的选择。这里只做一个简单例子,将字符串全部变成大写。

1、定义tld的类 

定义的方法应该是static方法。

public class TestFunction {

    public static String stringUpperCase(String target){
return target.toUpperCase();
}
} 

2、添加tld标签

<?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"> <tlib-version>1.0</tlib-version>
<short-name>fu</short-name>
<uri>/WEB-INF/tags/function.tld</uri> <function>
<name>stringUpperCase</name>
<function-class>test.tld.TestFunction</function-class>
<function-signature>java.lang.String stringUpperCase(java.lang.String)</function-signature>
</function>
</taglib>

<short-name>表示声明标签的调用名称。   

<uri>表示tld标签的位置,tld标签应该定义在WEB-INF中。这里我放在WEB-INF的tags文件夹中。

<function-class>tld标签运行的方法的类。

<function-signature>声明了方法返回的类型,方法名,方法的参数。方法参数可以是List,int等。

3、web.xml中声明tld标签

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
<display-name></display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<jsp-config>
<taglib>
<taglib-uri>/tags/function</taglib-uri>
<taglib-location>/WEB-INF/tags/function.tld</taglib-location>
</taglib>
</jsp-config>
</web-app>

4、使用自定义tld标签

<%@ taglib prefix="fn" uri="/tags/function" %>

${fn:stringUpperCase(target) }

声明tld标签后,才开始使用。target是后台保存在request或session的字符串。

5、总结

好好使用tld标签能在关键时候使你的页面更加优雅,在多次使用某段jsp的代码,可以封装起来,使页面更加简洁,下次再次使用的时候更加方便。