java商品列表增删源码_springmvc使用list集合实现商品列表的批量修改
时间: 2024-05-07 10:21:49 浏览: 121
以下是一个使用Spring MVC和List集合实现商品列表的批量修改的示例代码:
Controller类:
```
@Controller
public class ProductController {
@Autowired
private ProductService productService;
@RequestMapping(value = "/product/list", method = RequestMethod.GET)
public ModelAndView productList() {
ModelAndView mav = new ModelAndView("productList");
List<Product> productList = productService.getProductList();
mav.addObject("productList", productList);
return mav;
}
@RequestMapping(value = "/product/update", method = RequestMethod.POST)
public ModelAndView updateProductList(@ModelAttribute("productList") List<Product> productList) {
ModelAndView mav = new ModelAndView("productList");
productService.updateProductList(productList);
mav.addObject("productList", productList);
return mav;
}
}
```
Product类:
```
public class Product {
private int id;
private String name;
private double price;
// getter and setter methods
}
```
Service类:
```
@Service
public class ProductService {
private List<Product> productList = new ArrayList<Product>();
public List<Product> getProductList() {
return productList;
}
public void updateProductList(List<Product> productList) {
this.productList = productList;
}
}
```
View页面:
```
<form:form method="POST" action="${pageContext.request.contextPath}/product/update">
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<form:form method="POST" action="${pageContext.request.contextPath}/product/update" modelAttribute="productList">
<c:forEach items="${productList}" var="product" varStatus="status">
<tr>
<td><form:input path="productList[${status.index}].id" value="${product.id}"/></td>
<td><form:input path="productList[${status.index}].name" value="${product.name}"/></td>
<td><form:input path="productList[${status.index}].price" value="${product.price}"/></td>
</tr>
</c:forEach>
</form:form>
</tbody>
</table>
<input type="submit" value="Update">
</form:form>
```
在这个示例中,我们使用了Spring MVC的ModelAndView来将List集合传递到View页面中。在View页面中,我们使用了JSTL的<c:forEach>标签来遍历产品列表,并使用Spring表单标签库中的<form:input>标签来生成输入框。当用户点击“Update”按钮时,我们使用Spring MVC的@ModelAttribute注解来捕获更新后的产品列表,并将其传递给Service类进行处理。
此示例中只包含了基本的增删功能,如需更多功能可以根据具体需求进行扩展。
阅读全文