Spring: 如何在JSP中获取模型属性并检查它是否为空?

Spring: How to get the model attribute and check if it is null in JSP?

最近才开始学习Spring框架。在我的控制器中,我写

@GetMapping("/users/{username}")
public String getUserByUsername(@PathVariable(value = "username") String username, ModelMap model) {
    User founduser = userRepository.findById(username)
            .orElseThrow(() -> new ResourceNotFoundException("User", "username", username));

    model.addAttribute("founduser",founduser);
    return "redirect:/profile";
}

然后,我尝试获取模型属性并将其打印在我的 JSP 中。

 <c:when test="${not empty founduser}">
             <table style="border: 1px solid;">
                <c:forEach var="one" items="${founduser}">
                    <tr>
                        <td>${one.username}</td>

                        <td>${one.createdAt}</td>
                    </tr>
                </c:forEach>
            </table>
        </c:when>

但是我发现test="${not empty founduser}一直是false,也就是说我的founduser属性是null。调试的时候显示模型添加founduser成功。

谁能告诉我为什么会出错?非常感谢!

首先,${not empty founduser} 将仅访问当前请求属性中的值。

然而你使用 redirect:/profile 来显示 JSP 。Redirect 意味着另一个新的请求将被发送到服务器。这个新请求不会通过 getUserByUsername 控制器,因此在这个新请求属性中没有 founduser 并且 JSP 找不到它。

要解决它,根据您的应用程序体系结构,您可以

  1. 不要在您的控制器中重定向,只需 return profile

  2. 如果确实需要重定向,请将值添加到 flash 属性,以便它们在重定向后仍然可以存活和访问:

    model.addFlashAttribute("founduser",founduser);