簡體   English   中英

如何使用jsp視圖檢查某個用戶是否已創建數據庫項

[英]How to check if certain user has made database items using jsp view

我有一個名為bookings的數據庫表,我正在嘗試但到目前為止找不到的是用if-else檢查,如果有某些用戶預訂,並將它們顯示在表中。

在此輸入圖像描述

所以我正在尋找這樣的東西:

(下面的半偽代碼)

<c:when test="${bookings.where(booking.userId == currentUserId) > 0}">
   display table with those items...
</c:when>

所以這將得到該用戶制作的所有表項

我如何在jsp視圖頁面中測試它?

提前致謝。

PS:顯示項目不是問題,我至少可以自己做:)

編輯后端部分

@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";
    }

首先,您可能應該在后端執行此操作並只傳遞已過濾的列表,但對於jsp方法,您可以使用forEach

例:

<c:forEach items="${bookings}" var="booking">
    <c:if test="${booking.userId == currentUserId}">
       ...
    </c:if>
</c:forEach>

編輯:問題已更新

要過濾后端中的預訂,您可以使用Stream API

List<Booking> bookings = bookingService.getAllBookings().stream()
        .filter(b -> b.getUserId() == currentUserId)
        .collect(Collectors.toList());
model.addAttribute("bookings", bookings);

編輯2.0:

實際上你甚至不應該在java中過濾它們。 由於從數據庫中獲取數據,因此應實現getBookingsForUserId()並使用WHERE子句對其進行過濾。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM