JavaWeb開發分享:WebJars,javaweb開發webjars
換了新工作之後,忙了好多,基本沒什麼時間上網了,寫Blog也變少了,還是以前那種技術驅動的環境好,大家都在積極學新技術,分享新技術。現在技術環境少了好多,學習激情也少了好多。不說了,寫寫自己學習的WebJars。
Java Web前端通常需要使用JS或CSS技術,例如jQuery, Backbone.js,Twitter Bootstrap等等。以前我都是將這些Web資源拷貝到Java Web項目的Webapp相應目錄下,這種通過人工方式拷貝可能會產生版本誤差,拷貝版本錯誤,漏拷等現象,前端頁面就無法正確展示。當然對我自己這個一定程度的強迫症人員來說,一大堆檔案夾和檔案變成了一個jar,感覺非常良好。
WebJars是將Web前端Javascript和CSS等資源打包成Java的Jar包,這樣在Java Web開發中我們可以藉助Maven這些依賴庫的管理,保證這些Web資源版本唯一性。基本原理如下:With any Servlet 3 compatible container, the WebJars that are in the WEB-INF/lib directory are automatically made available as static resources. This works because anything in a META-INF/resources directory in a JAR in WEB-INF/lib is automatically exposed as a static resource.下面說說如何具體使用WebJars,非常簡單。1.在maven的設定檔中定義要使用的js或者css對於的jar包
<dependency> <groupId>org.webjars</groupId> <artifactId>bootstrap</artifactId> </dependency> <dependency> <groupId>org.webjars</groupId> <artifactId>jquery-cookie</artifactId> </dependency> <dependency> <groupId>org.webjars</groupId> <artifactId>dojo</artifactId> </dependency>
2. 在jsp檔案中按以下路徑擷取jar中的檔案 (webjars/js or css jar name/version/detail file name)
<script type="text/javascript" src="<%=request.getContextPath() %>/webjars/jquery/1.9.0/jquery.min.js"></script><script type="text/javascript" src="<%=request.getContextPath() %>/webjars/bootstrap/3.0.2/js/bootstrap.min.js"></script> <script type="text/javascript" src="<%=request.getContextPath() %>/webjars/jquery-cookie/1.3.1/jquery.cookie.js"></script>
PS:處理靜態資源大型網站肯定不是Java伺服器,基本都是用apache或者nginx等來處理靜態處理,效能更好。對於小網站,可以直接使用WebJars。