遇到个需要传输list的问题,困扰了两天,网上各种各样,今天突然看到这位大神的,然后根据情况自己终于解决了难题,现在结合大神的,大概总结一下,以便下次参考!
转自:
https://blog.csdn.net/HANHUABAO1122/article/details/104379861
在Jsp页面传递需要到Action的List中的数据,书写格式为
```java
<s:textfield name="%{'books['+#status.index+'].title'}" /> 或者
<pre name="code" class="html" style="font-size: 18px;"><s:textfield name="books[#status.index].title" />
```
在这里为Book对象传递的有3个值,书写语法都一样,代码如下
```java
<body>
<h1>图书订购系统</h1>
<s:form action="bookConfirm" method="post" theme="simple">
<table>
<tr>
<td>书名</td>
<td>价格</td>
<td>数量</td>
</tr>
<s:iterator value="new int[5]" status="status">
<tr>
<td><s:textfield name="%{'books['+#status.index+'].title'}" /></td>
<td><s:textfield name="%{'books['+#status.index+'].price'}" /></td>
<td><s:textfield name="%{'books['+#status.index+'].amount'}" /></td>
</tr>
</s:iterator>
<tr>
<td colspan="3"><s:submit value="订阅图书" /></td>
</tr>
</table>
</s:form>
</body>
```
书籍的实例对象定义为
```java
public class Book {
private String title;
private float price;
private int amount;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public int getAmount() {
return amount;
}
public void setAmount(int amount) {
this.amount = amount;
}
}
```
请求的Action中定义列表List有两种不同的方式,如果我们在定义列表的时候已经为List限定了泛型,那么书写的格式如下(1)即可,否则需要如(2)代码所示,还要为Action添加一个ObjectTypeDeterminer对象来限定集合元素的类型。
```java
(1)
public class BookConfirm extends ActionSupport {
private static final long serialVersionUID = 1L;
private List<Book> books =null;
public List<Book> getBooks() {
return books;
}
public void setBooks(List<Book> books) {
System.out.println("enter");
this.books = books;
}
}
(2)
public class BookConfirm extends ActionSupport {
private static final long serialVersionUID = 1L;
private List books =null;
public List getBooks() {
return books;
}
public void setBooks(List books) {
System.out.println("enter");
this.books = books;
}
}
```
在Action所在目录下定义一个文件BookConfirm-conversion.properties,
文件命名格式为:classname-conversion.properties文件内添加语句
Element_books=com.addbooks.Book
(此句非常重要,一定得添加上)
然后action便会自动set属性值!