通常我們遇到的情況是:必須在運行時創(chuàng)建一個列表或數(shù)組,并迭代列表。你可以使用腳本創(chuàng)建列表或數(shù)組,也可以使用
generator標簽。
創(chuàng)建Action類
package cn.w3cschool.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;
}
}
創(chuàng)建視圖
讓我們用
HelloWorld.jsp來演示如何使用
generator標簽:
<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title>Hello World</title>
</head>
<body>
<h2>Example of Generator Tag</h2>
<h3>The colours of rainbow:</h3>
<s:generator val="%{'Violet,Indigo,Blue,
Green,Yellow,Orange,Red '}" count="7"
separator=",">
<s:iterator>
<s:property /><br/>
</s:iterator>
</s:generator>
</body>
</html>
這里我們創(chuàng)建一個
generator標簽,要求它解析包含形成彩虹的顏色列表,用逗號分隔字符串。我們告訴生成器標簽,分隔符是“,”,并需要列表中的所有七個值。如果我們只對前三個值感興趣,那么我們將計數(shù)設(shè)置為3。在generator標簽中,我們使用迭代器來迭代generator標簽創(chuàng)建的值,然后打印屬性的值 。
配置文件
你的
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="helloworld" extends="struts-default">
<action name="hello"
class="com.tutorialspoint.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>
右鍵單擊項目名稱,然后單擊“Export”> “WAR File”以創(chuàng)建WAR文件。然后在Tomcat的webapps目錄中部署WAR文件。最后,啟動Tomcat服務(wù)器并嘗試訪問URL http://localhost:8080/HelloWorldStruts2/hello.action,將顯示以下界面:
更多建議: