怎樣使用自定義標簽簡化 js、css 引入?
國慶將至,工作興致全無,來總結點項目裏平時不起眼幹貨。
前端引入 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>
引入方式:(上述標簽詳細屬性和使用方法:http://blog.sina.com.cn/s/blog_76b2c4810101a8so.html)
<!-- 相對路徑引入 -->
<%@ taglib prefix="fnc" uri="/WEB-INF/tlds/core.tld" %>
<!-- 唯一 url 引入 -->
<%@ taglib prefix="fnc" uri="http://com.rambo.spm/core/tags" %>
OK,在理解底層的處理流程的前提下,具體項目具體場景都可以進行自定義標簽的設計。
設計標簽的目的當然是簡化前端、整合共有功能、加快項目推進,當然設計的好壞需要項目去沈澱和積累。
怎樣使用自定義標簽簡化 js、css 引入?