繁体   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