一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

Spring MVC使用jstl标签c:forEach遍历输出双层嵌套List数据方式代码示例

时间:2022-06-29 02:14:43 编辑:袖梨 来源:一聚教程网

本篇文章小编给大家分享一下Spring MVC使用jstl标签c:forEach遍历输出双层嵌套List数据方式代码示例,文章代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。

具体操作步骤如下:

1、创建Controller

import java.util.ArrayList;
import java.util.List; 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; 
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping; 
import com.mahaochen.springmvc.domain.Goods;
import com.mahaochen.springmvc.domain.Inventory;
 
@Controller
@RequestMapping("/shop")
public class ShoppingController { 
 
 @RequestMapping("/shoppingCart")
 public String getShoppingCart(HttpServletRequest request,  HttpServletResponse response,Model model){  
  model.addAttribute("list", generateData());  
  return "shoppingCart";
 }
 private List generateData(){
   List inventories = new ArrayList();
  for(int i=0 ; i<2 ; i++){
   switch (i) {
   case 0:
    Inventory inventory1 = new Inventory();
    inventory1.setInventoryType("水果");
    List goodsList1 = new ArrayList(); 
    for(int j=0;j<5;j++){
     Goods goods = new Goods();
     goods.setGoodsName("苹果"+j);
     goodsList1.add(goods);
    }
    inventory1.setGoodList(goodsList1);
    inventories.add(inventory1);
    break;
   default:
    Inventory inventory2 = new Inventory();
    inventory2.setInventoryType("蔬菜");
    List goodsList2 = new ArrayList(); 
    for(int j=0;j<5;j++){
     Goods goods = new Goods();
     goods.setGoodsName("茄子"+j);
     goodsList2.add(goods);
    }
    inventory2.setGoodList(goodsList2);
    inventories.add(inventory2);
    break;
   }
  }
  return inventories;
 }
}

2、创建对应的jsp页面

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 




购物车



${item.inventoryType}
--${var.goodsName }

注意事项:

JSTL1.1的库 在JSP2.0(Servlet 2.4)及以后(推荐用JSTL1.1及以上)用:

<%@taglibprefix="c" uri="http://java.sun.com/jsp/jstl/core"%>  

web.xml




在 Servlet2.3及以前,

<%@taglibprefix="c" uri="http://java.sun.com/jstl/core"%>  

与2.4比较,以后版本路径少了jsp。

web.xml

  
  
        
  

不然会出现以下错误:

org.apache.jasper.JasperException:/WEB-INF/jsp/shoppingCart.jsp(line: 10, column: 1) According to TLD or attribute directive in tag file,attribute items does not accept any expressions

springMVC的forEach不能正常显示

1、问题

在进行springMVC的forEach联系时,出现如下错误

org.apache.jasper.JasperException: An exception occurred processing JSP page /WEB-INF/jsp/index.jsp at line 12

    
         

2、解决

forEach的获取是通过getter来进行的,在实体类中添加getter方法即可。

${student.id} ${student.name}