-
原文鏈接:https://www.cnblogs.com/guaishoubiubiu/p/8721277.html
TLD術語解釋:標簽庫描述文件,如要在JSP頁面中使用自定義JSP標簽,必須首先定義實現標簽的類,然后在標簽庫描述文件(TLD)中
將寫好的類映射成JSP標簽,最后在JSP文件中使用定義好的標簽,就可以生成動態的JSP內容。
作用:在jsp頁面能顯示數據庫的東西,省了不少事
1.定義tld,和web.xml一個位置,約定於配置文件
<?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.1</tlib-version> <short-name>myfn</short-name> <uri>http://www.itheima.com/jsp/functions</uri> <function> <name>findCategoryNameById</name> #在jsp頁面中想要使用這個Functions中的findCategoryById()這個方法的話,需要使用這里指定的名稱 <function-class>com.itheima.web.Functions</function-class> #自定義類的位置 <function-signature>java.lang.String findCategoryNameById(java.lang.String)</function-signature> #自定義類中的一個方法 </function> </taglib>
2.定義對應的實體類
public class Functions { public static String findCategoryNameById(String categoryId){ BusinessService s = new BusinessServiceImpl(); Category c = s.findCategoryById(categoryId); return c.getName(); } }
3.jsp中使用
導入標簽<%@ taglib uri="http://www.itheima.com/jsp/functions" prefix="myfn"%> 使用標簽${myfn:findCategoryNameById(b.categoryId)}
節省了很多代碼,而且增加了代碼的可重復利用性