SetTagAction.java
package com.tw511.common.action; import com.opensymphony.xwork2.ActionSupport; public class SetTagAction extends ActionSupport{ private String msg = "Struts 2 is a funny framework"; public String getMsg() { return msg; } public String execute() throws Exception { return SUCCESS; } }
set.jsp
<%@ taglib prefix="s" uri="/struts-tags" %> <html> <head><title>www.tw511.com</title> </head> <body> <h1>Struts 2 set tag example</h1> <div><div class="ads-in-post hide_if_width_less_800"> <script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script> <!-- 728x90 - After2ndH4 --> <ins class="adsbygoogle hide_if_width_less_800" data-ad-client="ca-pub-2836379775501347" data-ad-slot="3642936086" data-ad-region="yiibairegion"></ins> <script> (adsbygoogle = window.adsbygoogle || []).push({}); </script> </div></div><h2>1. <s:set var="varMsg" value="msg" /></h2> <s:set var="varMsg" value="msg" /> <s:property value="varMsg" /> <h2>2. <s:set var="varUrl" value="%{'https://www.tw511.com'}" /></h2> <s:set var="varUrl" value="%{'https://www.tw511.com'}" /> <s:property value="varUrl" /> </body> </html>
它是如何工作的?
1. <s:set var=」varMsg」 value=」msg」 />
呼叫動作的 getMsg()方法返回的值賦給變數名為 「varMsg「.
2. <s:set var=」varUrl」 value=」%{‘https://www.tw511.com’}」 />
寫死字串,並將其分配給一個名為變數 「varUrl「.
例如,
public class SetTagAction extends ActionSupport{ private String msg; public String setMsg(String msg) { this.msg = msg; } ...
<s:set var="msg" value="%{'this is a message'}" />
這是錯誤的,<s:set>標籤將不會呼叫setMsg()方法,它只會以名為「msg」分配「value」到變數。沒有動作屬性值。
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <constant name="struts.devMode" value="true" /> <package name="default" namespace="/" extends="struts-default"> <action name="setTagAction" class="com.tw511.common.action.SetTagAction" > <result name="success">pages/set.jsp</result> </action> </package> </struts>
http://localhost:8080/struts2settag/setTagAction.action
在瀏覽器中開啟上面的網址,輸出結果如下:
程式碼下載 - http://pan.baidu.com/s/1mgs6Tle