param标签可用于参数其他标签。包括标签和bean标签,这种标签的例子。让我们以同样的例子我们已经讨论,同时讨论bean标签。
package com.h3.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:
<%@ page contenttype="text/html; charset=utf-8" %> <%@ taglib prefix="s" uri="/struts-tags" %> <html> <head> <title>hello world</title> </head> <body> <s:bean name="org.apache.struts2.util.counter" var="counter"> <s:param name="first" value="20"/> <s:param name="last" value="25" /> </s:bean> <ul> <s:iterator value="#counter"> <li><s:property /></li> </s:iterator> </ul> </body> </html>
接下来让我们看看employees.jsp包含以下内容:
<%@ page contenttype="text/html; charset=utf-8"%> <%@ taglib prefix="s" uri="/struts-tags"%> <html> <head> <title>employees</title> </head> <body> <p>an example of the include tag: </p> <s:include value="helloworld.jsp"/> </body> </html>
struts.xml中应该像这样:
<?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="helloworld" extends="struts-default"> <action name="hello" class="com.h3.struts2.helloworldaction" method="execute"> <result name="success">/helloworld.jsp</result> </action> <action name="employee" class="com.h3.struts2.employee" method="execute"> <result name="success">/employee.jsp</result> </action> </package> </struts>
web.xml 应该像这样:
<?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>
右键点击项目名称,并单击“导出”>war文件创建一个war文件。然后部署此war在tomcat的webapps目录下。最后,启动tomcat服务器和尝试访问url http://localhost:8080/helloworldstruts2/hello.action。这会给出以下画面:
在这个例子中,我们实例化一个新的org.apache.struts2.util.counter bean的实例。然后我们的第一个属性设置为20和25的最后一个属性。这意味着计数器的值分别为20,21,22,23,24和25。我们给一个名为“counter”的bean。 struts的bean标签bean的实例化,并把它值栈中的。现在我们可以使用迭代器去,通过计数器bean的nd打印出计数器的值。