Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Struts2 非表單標籤:靈活使用 component 自訂元件

component 標籤是什麼

Struts2 的 <s:component> 標籤用來使用自訂元件,是非常靈活的一招。如果某個效果片段會被反覆使用,就可以把它定義成一個自訂元件,然後在頁面中用 component 標籤呼叫。

由於自訂元件仍然是基於主題(theme)與模板(template)管理,使用時常需要指定三個屬性:

  • theme:自訂元件使用的主題,不指定時預設為 xhtml。
  • templateDir:自訂元件的主題目錄,不指定時預設使用系統主題目錄,即 template 目錄。
  • template:自訂元件所使用的模板。

此外,還可以在 component 標籤內用 <s:param> 子標籤傳入額外參數;要在模板中取值,寫法固定是 $parameters.paramname 或 $parameters['paramname']。

提示:自訂模板可以用 FreeMarker、JSP、Velocity 三種技術撰寫。

四種載入方式

以下 JSP 片段示範了 component 標籤的四種典型用法:

<!-- 使用自訂主題、自訂主題目錄,從 Web 應用根路徑載入 ftl 模板 -->
<s:component
    theme="customTheme"
    templateDir="customTemplateDir"
    template="ftlCustomTemplate">
  <s:param name="list"
    value="{'Spring2.0寶典', '輕量級J2EE企業應用實戰', '基於J2EE的Ajax寶典'}" />
</s:component>
<hr/>

<!-- 使用自訂主題、自訂主題目錄,從 Web 應用根路徑載入 JSP 模板 -->
<s:component
    theme="customTheme"
    templateDir="customTemplateDir"
    template="jspCustomTemplate.jsp">
  <s:param name="list"
    value="{'Spring2.0寶典', '輕量級J2EE企業應用實戰', '基於J2EE的Ajax寶典'}" />
</s:component>
<hr/>

<!-- 使用預設主題(xhtml)、預設主題目錄(template),從 Web 應用中載入 JSP 模板 -->
<s:component template="mytemplate.jsp">
  <s:param name="list"
    value="{'Spring2.0寶典', '輕量級J2EE企業應用實戰', '基於J2EE的Ajax寶典'}" />
</s:component>
<hr/>

<!-- 使用自訂主題、自訂主題目錄,從 /WEB-INF/classes 載入 ftl 模板 -->
<s:component
    theme="myTheme"
    templateDir="myTemplateDir"
    template="myAnotherTemplate">
  <s:param name="list"
    value="{'Spring2.0寶典', '輕量級J2EE企業應用實戰', '基於J2EE的Ajax寶典'}" />
</s:component>

模板檔本身怎麼寫

頁面上用到的兩個 FreeMarker 模板都使用了 FreeMarker 標籤;另外兩個 JSP 模板只是載入位置不同,程式碼相同,如下:

<%-- 設置頁面編碼 --%>
<%@ page contentType="text/html; charset=GBK" language="java"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<div>
  <b>JSP自定義模板<br>
  請選擇您喜歡的圖書<br></b>
  <!-- 使用 select 標籤迭代輸出 list 參數傳進來的集合 -->
  <s:select list="parameters.list"/>
</div>

struts2 檔案上傳(保存為 BLOB 格式) https://www.linuxidc.com/Linux/2014-06/102905.htm

Struts2 的入門實例 https://www.linuxidc.com/Linux/2013-05/84618.htm

Struts2 實現 ModelDriven 介面 https://www.linuxidc.com/Linux/2014-04/99466.htm

遇到的 Struts2 檔案下載亂碼問題 https://www.linuxidc.com/Linux/2014-03/98990.htm

Struts2 整合 Spring 方法及原理 https://www.linuxidc.com/Linux/2013-12/93692.htm

Struts2 註解模式的幾個知識點 https://www.linuxidc.com/Linux/2013-06/85830.htm

Struts 的詳細介紹:請點這裡
Struts 的下載地址:請點這裡

Copyright © Linux教程網 All Rights Reserved