简体   繁体   中英

How to access a variable of two class in JSP loop

I've got two classes:

 public Car
      Integer number;
      String  name;

  public Parking
      Integer parkingNumber;
      String address;

I sent to my JSP one List of Parking and one List of Car

 List<Parking> parkingList= new ArrayList<Parking>();
 List<Car> carList= new ArrayList<Car>();

but full of values(they are not important for the example)

Model.addAttribute("parkingList", parkingList);
Model.addAttribute("carList", carList);`

How can i access inside a loop(foreach) to a car->name of a car with a car->number = a defined Parking->parkingNumber (assume for example this is 5) ?

   <c:forEach items="${parkingList}" var="park" varStatus="status"> 
       <p> $carList[park.parkingNumber=5].name</p>
  </c:forEach>

Is it correct? Unluckly I can't use another Foreach because the car.name value must be wrote in the page only one time.

Below line in your code seems to be incorrect

 <p> $car[park.parkingNumber=5].name</p>

Because you are setting below values in model

Model.addAttribute("parkingList", parkingList); 
Model.addAttribute("car", car);

where you are putiing single Car object in model and you are trying to access it like an array $car[park.parkingNumber=5].name

You can directly say car.name

Try this,

<c:forEach items="${parkingList}" var="park" varStatus="parkStatus"> 
   <c:forEach items="${carList}" var="car" varStatus="carStatus"> 
      <c:if test="car.number eq park.parkingNumber">
         <p><c:out value="car.name" /></p>
      </c:if>
   </c:forEach>
</c:forEach>

OR

If you do not wish to use multiple foreach loops, on server side, you can use Car class in Parking class like,

public Parking
  Integer parkingNumber;
  String address;
  List<Car> carList = new ArrayList<>();

And put the Car 's list in the Parking object where all cars having same number as parkingNumber.

for(Parking parking : parkingList) {
  for(Car car : carList) {
    if (car.getNumber() == parking.getParkingNumber()) {
      parking.getCarList().add(car);
    }
  }
}

Then you have to just iterate this once and you will get all the cars which has same parking number.

<c:forEach items="${parkingList}" var="park" varStatus="parkStatus"> 
   <c:forEach items="${park.carList}" var="car" varStatus="carStatus"> 
      <p><c:out value="car.name" /></p>
   </c:forEach>
</c:forEach>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM