URL標(biāo)簽是負(fù)責(zé)生成URL字符串。這樣做的好處是,你可以提供參數(shù)標(biāo)簽。我們通過一個例子來說明使用的URL標(biāo)簽。
package com.yiibai.struts2; public class HelloWorldAction{ private String name; public String execute() throws Exception { return "success"; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
helloWorld.jsp包含以下內(nèi)容:
<%@ page contentType="text/html; charset=UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags"%> <html> <head> <title>Hello World</title> </head> <body> <s:url id="login" action="login" var="myurl"> <s:param name="user">Zara</s:param> </s:url> <a href='<s:property value="#myurl"/>'> <s:property value="#myurl"/></a> </body> </html>
在這里,我們生成一個網(wǎng)址鏈接“login.action”。我們已經(jīng)給這個url名稱“myurl”。這是為了讓我們可以重用這個網(wǎng)址鏈接在多個地方的jsp文件。然后,我們提供的url參數(shù)調(diào)用用戶。參數(shù)值實(shí)際上追加到查詢字符串,可以看到從上面的輸出。
主要是有用是當(dāng)你想創(chuàng)建一個bean屬性值的基礎(chǔ)上動態(tài)超鏈接的URL標(biāo)簽。
你的struts.xml中應(yīng)該像這樣:
<?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="helloaction" extends="struts-default"> <action name="hello" class="com.yiibai.struts2.HelloWorldAction" method="execute"> <result name="success">/HelloWorld.jsp</result> </action> </package> </struts>
你的web.xml 應(yīng)該像這樣:
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>Struts 2</display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <filter> <filter-name>struts2</filter-name> <filter-class> org.apache.struts2.dispatcher.FilterDispatcher </filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
右鍵點(diǎn)擊項(xiàng)目名稱,并單擊Export > WAR File創(chuàng)建一個WAR文件。然后部署這個WAR在Tomcat的webapps目錄下。最后,啟動Tomcat服務(wù)器和嘗試訪問URL http://localhost:8080/HelloWorldStruts2/hello.action。這會給你以下畫面: