1. 程式人生 > >【引用】Struts2中的連結標籤 和

【引用】Struts2中的連結標籤 和

普通連結 Web程式中最普通的應用是連結到其他頁面,下面看Welcome.jsp
<%@ page contentType="text/html; charset=UTF-8" %> <%@ taglib prefix="s" uri="/struts-tags" %> <html> <head> <title>Welcome</title> <link href="<s:url value="/css/tutorial.css"/>" rel="stylesheet" type="text/css"/> </head>
<body> <h3>Commands</h3> <ul> <li><a href="<s:url action="Login_input"/>">Sign On</a></li> <li><a href="<s:url action="Register"/>">Register</a></li> </ul> </body> </html>
1.1說明 1<%@ taglib prefix="s" uri="/struts-tags" %>
此句表示匯入struts標籤,並以s為字首。即以s為字首的標籤均來自struts標籤庫。 2<link href="<s:url value="/css/tutorial.css"/>" rel="stylesheet" type="text/css"/> 此句表示利用url標籤匯入一個路徑,連結到一個檔案,注意此路徑為專案下的絕對路徑。 3<a href="<s:url action="Login_input"/>">Sign On</a> 此句表示利用url標籤連結到一個action 1.2註冊action 我們在struts.xml
中註冊一個action來顯示welcome.jsp
<action name="Welcome"> <result>/example/Welcome.jsp</result> </action>
注意此action註冊在package example下,所以在位址列中敲入http://localhost:8080/StrutsHelloWorld/example/Welcome.actionStrutsHelloWorldproject名),會導向到Welcome.jsp。 2.使用萬用字元 對於上面的action註冊,我們也可以用下面的語句代替。
<action name="*"> <result>/example/{1}.jsp</result> </action>
此句的意思是,如果在沒有找到匹配的action名稱的情況下,預設呼叫action名稱.jsp。第一句中星號指任意,而第二句中{1}指代第一句中星號指代的內容。
    舉個例子,如果在位址列中敲入
http://localhost:8080/StrutsHelloWorld/example/1.action,則系統查詢struts.xml,發現沒有name1action,即最後呼叫name為星號的這個action,根據此action,將輸出/example/1.jsp
或者讀者可以直接點選Welcome.jsp中的兩個超連結,系統將會報錯找不到Login_input.jspRegister.jsp。因為這兩個action還沒有註冊,也沒有相應的jsp檔案。 3.帶引數的連結 超連結後面帶有引數大家不會陌生,諸如http://www.apache.com/?language=ch。這個連結後面帶有一個language引數,其值為ch。你可以通過request.getParameter(“language”)找到引數值。下面演示在struts2中如何設定帶引數的連結。看HelloWorld.jsp
<%@ taglib prefix="s" uri="/struts-tags"%> <html> <head> <title>Hello World!</title> </head> <body> <h2><s:property value="message" /></h2> <h3>Languages</h3> <ul> <li> <s:url id="url" action="HelloWorld"> <s:param name="request_locale">en</s:param> </s:url> <s:a href="%{url}">English</s:a> </li> <li> <s:url id="url" action="HelloWorld"> <s:param name="request_locale">es</s:param> </s:url> <s:a href="%{url}">Espanol</s:a> </li> </ul> </body> </html>

3.1
說明
1<s:url id="url" action="HelloWorld"> <s:param name="request_locale">en</s:param> </s:url> 此段表示設定一個url標籤指向名為HelloWorldaction,此標籤帶一個id取名為url,後面會用到。帶一個引數request_locale,其值為en 2<s:a href="%{url}">English</s:a> 此句用到了struts2的超連結標籤,連線的地址即為1url,點選English,發出的資訊為:http://localhost:8080/StrutsHelloWorld/example/HelloWorld.actionrequest_locale=en 3.2註冊actionstruts.xml <struts> <package name="example" namespace="/example" extends="struts-default"> <action name="HelloWorld" > <result>/example/HelloWorld.jsp</result>
</action>
       </package>
</struts>