I have a database table called bookings, and what i'm trying to do but couldn't find so far, is to check with if-else, if there are bookings made by certain user, and display them in a table.
So i'm looking for something like this:
(semi-pseudo code below)
<c:when test="${bookings.where(booking.userId == currentUserId) > 0}">
display table with those items...
</c:when>
so this would get me all the table items made by that user
How can i test this in a jsp view page?
Thanks in advance.
PS: displaying the items is not a problem, i can at least do that on my own :)
EDIT backend part :
@GetMapping("/bookings")
public String getAllBookings(Model model) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
UserDetails userDetail = (UserDetails) auth.getPrincipal();
User user = userService.findByUsername(userDetail.getUsername());
int currentUserId = user.getId();
List<Booking> bookings = bookingService.getAllBookings();
model.addAttribute("bookings", bookings);
model.addAttribute("currentUserId", currentUserId);
model.addAttribute("currentUser", getPrincipal());
return "booking-list";
}
First of all you probably should do this on backend and just pass filtered list, but for the jsp approach you can use forEach
.
Example:
<c:forEach items="${bookings}" var="booking">
<c:if test="${booking.userId == currentUserId}">
...
</c:if>
</c:forEach>
Edit: question updated
To filter bookings in the backend you could use Stream API
:
List<Booking> bookings = bookingService.getAllBookings().stream()
.filter(b -> b.getUserId() == currentUserId)
.collect(Collectors.toList());
model.addAttribute("bookings", bookings);
Edit 2.0:
Actually you shouldn't even filter them in java. Since you take the data from database, you should implement getBookingsForUserId()
and use WHERE
clause to filter them.