怎樣使用自訂標籤簡化 js、css 引入?,jscss
國慶將至,工作興緻全無,來總結點項目裡平時不起眼乾貨。
前端引入 js 、css 一般是這樣:
<script type="text/javascript" src="webContent 相對路徑"></script><link type="text/css" href="webContent 相對路徑" rel="stylesheet"/>
簡化後的 js 、css 引入姿勢:
<fnc:script path="靜態資源相對路徑"/><fnc:style path="靜態資源相對路徑"/>
看起來是不是順眼多了,自訂標籤引入檔案的方式,好處和擴充點還有很多,且聽我慢慢道來。
該自訂標籤基於 jsp-api,要沒使用過 jsp 的同學,其實也沒必要往下翻了,都挺忙的對吧。
1. 繼承 TagSupport 設計標籤處理類
javax.servlet.jsp.tagext.TagSupport 作為自訂標籤核心關注類,實現了 IterationTag、Tag、JspTag 介面。
在實現的這些介面中,有些表示狀態的常量需要介紹一下,這樣你的理解會更明亮。
int SKIP_BODY = 0; //跳過了開始和結束標籤之間的代碼int EVAL_BODY_INCLUDE = 1;//需要處理標籤體int SKIP_PAGE = 5;//忽略剩下的頁面int EVAL_PAGE = 6;//繼續輸出下面的頁面int EVAL_BODY_AGAIN = 2;//反覆執行所處的方法
配上我這活動圖表和上述狀態代碼然後結合介面方法,應該大體上明白 sun 底層對 jsp 標籤整個處理流程了吧。
像 struts 的 <s:> 標籤系列、webwork 的<ww:> 標籤系列、JSTL 的 <s:> 標籤系列等等...都是在上述流程下做的擴充。
好了,底層機制剖析結束,還是迴歸主題,繼承 TagSupport 的自訂標籤處理類如下。
public class StyleTag extends TagSupport { private String path; public StyleTag() { } public int doEndTag() throws JspException { JspWriter writer = this.pageContext.getOut(); String contextPath = this.pageContext.getRequest().getServletContext().getContextPath(); try { if (StrUtil.isNotBlank(path)) { if (this.path.startsWith("/")) { writer.write("<link rel='stylesheet' type='text/css' href='" + contextPath + "/static" + this.path + "'/>"); } else writer.write("<link rel='stylesheet' type='text/css' href='" + this.path + "'/>"); } } catch (Throwable var9) { System.out.println("Output style Error:" + var9.getMessage()); } finally { this.path = null; } return TagSupport.EVAL_PAGE; } //....getter/setter}
我想做的事情比較簡單,這裡重寫 doEndTag 方法就足夠了,實際項目情境涉及複雜,這裡就不進行描述了。
2. 編寫 tld 標籤庫定義
當你想在 jsp 頁面使用時還需要編寫與後端處理類對應的 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"> <description>項目核心標籤庫</description> <display-name>JSTL functions core</display-name> <tlib-version>1.1</tlib-version> <short-name>fnc</short-name> <uri>http://com.rambo.spm/core/tags</uri> <tag> <description>簡化css在頁面的引入方式</description> <name>style</name> <tag-class>com.rambo.spm.core.tag.StyleTag</tag-class> <body-content>empty</body-content> <attribute> <description>css相對static的路徑</description> <name>path</name> <required>true</required> <rtexprvalue>true</rtexprvalue> </attribute> </tag></taglib>
引入方式:
<!-- 相對路徑引入 --><%@ taglib prefix="fnc" uri="/WEB-INF/tlds/core.tld" %><!-- 唯一 url 引入 --><%@ taglib prefix="fnc" uri="http://com.rambo.spm/core/tags" %>
OK,在理解底層的處理流程的前提下,具體項目具體情境都可以進行自訂標籤的設計。
設計標籤的目的當然是簡化前端、整合共有功能、加快項目推進,當然設計的好壞需要項目去沉澱和積累。