原文連接:https://www.it610.com/article/442039.htmjava
步驟以下:
一、寫tld文檔:用來指定標籤的名字,標籤庫等。web
二、寫標籤處理器類。jsp
三、配置到web.xml中
四、在jsp中使用新定義的標籤ide
例:實現一個自定義標籤 功能以下 若是字符串長度超過規定長,則截取,並根據要求添加省略號ui
tls文檔:this
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN" "http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd"> <taglib> <tlib-version>1.0</tlib-version> <jsp-version>2.0</jsp-version> <short-name>ip</short-name> <uri>http://www.xx.tag</uri> <tag> <name>stringCut</name> <tag-class>com.xx.utils.jstl.JSTLStringCut</tag-class> <attribute> <name>str</name> <required>false</required> <rtexprvalue>true</rtexprvalue><!-- 是否支持el表達式 --> <type>java.lang.String</type> <description>輸入字符串</description> </attribute> <attribute> <name>length</name> <required>true</required> <rtexprvalue>true</rtexprvalue> <type>java.lang.Integer</type> <description>要顯示字符串的長度</description> </attribute> <attribute> <name>showDot</name> <required>true</required> <rtexprvalue>true</rtexprvalue> <type>java.lang.Boolean</type> <description>是否顯示點號</description> </attribute> </tag> </taglib>
標籤處理器類:spa
package com.xx.utils.jstl; import java.io.IOException; import javax.servlet.jsp.JspException; import javax.servlet.jsp.tagext.BodyTagSupport; public class JSTLStringCut extends BodyTagSupport{ private String str ; private Integer length ; private Boolean showDot; @Override public int doStartTag() throws JspException { System.out.println(str); System.out.println(length); System.out.println(showDot); try { if(str==null){ //do nothing }else{ if(str.length()>length){ str=str.substring(0,length); if(showDot){ str=str+"..."; } } pageContext.getOut().print(str); } } catch (IOException e) { e.printStackTrace(); } return BodyTagSupport.EVAL_BODY_INCLUDE;//執行標籤內容 } @Override public int doEndTag() throws JspException { return BodyTagSupport.EVAL_BODY_INCLUDE; } public String getStr() { return str; } public void setStr(String str) { this.str = str; } public Integer getLength() { return length; } public void setLength(Integer length) { this.length = length; } public Boolean getShowDot() { return showDot; } public void setShowDot(Boolean showDot) { this.showDot = showDot; } }
配置到web.xmlcode
<jsp-config> <taglib> <taglib-uri>http://www.xx.tag</taglib-uri> <taglib-location>/WEB-INF/tags/string-cut.tld</taglib-location> </taglib> </jsp-config>
jsp中使用標籤xml
jsp頁面頂部加入:htm
<%@ taglib uri="http://www.xx.tag" prefix="ip" %>
<ip:stringCut str="${str}" length="10" showDot="true"></ip:stringCut>