- web.xml文件
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
- struts.xml文件
<action name="Admin1">
<result>/jsp/Admin.jsp</result>
</action>
<action name="Admin2" class="app07a.Admin2">
<result name="input">/jsp/Admin.jsp</result>
<result name="success">/jsp/Confirmation.jsp</result>
</action>
<action name="Admin1b">
<result>/jsp/Admin1b.jsp</result>
</action>
- 动作类Admin2.java
package app07a;
import java.util.Collection;
import com.opensymphony.xwork2.ActionSupport;
public class Admin2 extends ActionSupport {
private Collection employees;
public Collection getEmployees() {
return employees;
}
public void setEmployees(Collection employees) {
this.employees = employees;
}
public String execute(){
return SUCCESS;
}
}
特别注意,这个动作类里面的属性是一个Collection,思考一下便会明白这个动作类的属性肯定是一个存储真实bean的集合。但是出现了一个问题:我们如何做到让来自jsp页面的struts标签映射到这个Collection中的元素的属性呢??
struts解决方案是:在自定义的类型转换配置文件中告诉struts要映射的Collection中元素的类型。看下面:
- Admin.jsp页面
<s:fielderror/>
<s:form theme="simple" action="Admin2">
<table>
<tr>
<th>FirstName</th><th>LastName</th><th>BirthDate</th>
</tr>
<tr>
<td>
<s:textfield name="employees[0].firstName" key="firstName"/>
</td>
<td>
<s:textfield name="employees[0].lastName" key="lastName"/>
</td>
<td>
<s:textfield name="employees[0].birthDate" key="birthDate"/>
</td>
</tr>
<tr>
<td>
<s:textfield name="employees[1].firstName" key="firstName"/>
</td>
<td>
<s:textfield name="employees[1].lastName" key="lastName"/>
</td>
<td>
<s:textfield name="employees[1].birthDate" key="birthDate"/>
</td>
</tr>
<tr>
<td colspan="3"><s:submit/></td>
</tr>
</table>
</s:form>
这个jsp文件,同时提交两个对象的属性。
- 告诉struts上面jsp中struts标签映射到Collection集合中的哪个类型的元素。配置文件:Admin2-conversion.properties
Element_employees=app07a.Employee
这个配置文件告诉struts来自jsp中struts标签映射到Collection属性中的元素类型是一个完全限制名的某类
其中,Element_动作类中的集合属性对象名,表示的是这个对象的元素类型是等号后面类的实例。
- 另一个jsp显示内容的页面
<table>
<s:iterator value="employees">
<tr>
<td>
<s:property value="firstName"/>
<s:property value="lastName"/>
<s:date name="birthDate" format="MMM dd,yyyy"/>
</td>
</tr>
</s:iterator>
</table>
特别注意:本案例中也用了和上一章节中同样的自定义的类型转换器,来转换日期类型。
运行结果:
进一步学习
Admin.jsp页面:
<h4>Add Employees</h4>
<s:fielderror/><!--档类型转换错误时候,出错提示信息会通过这句便签显示,然后下面的语句将不再执行-->
<s:form theme="simple" action="Admin2">
<table>
<s:iterator value="new int[#parameters.count[0]]" status="stat">
<tr>
<td><s:textfield name="%{'employees['+#stat.index+'].firstName'}"/></td>
<td><s:textfield name="%{'employees['+#stat.index+'].lastName'}"/></td>
<td><s:textfield name="%{'employees['+#stat.index+'].birthDate'}"/></td>
</tr>
</s:iterator>
<tr>
<td colspan="s"><s:submit/></td>
</tr>
</table>
</s:form>
运行结果: