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

Spring:如何获取模型属性并检查它在JSP中是否为null?,spring,spring-boot,jsp,jstl,Spring,Spring Boot,Jsp,Jstl,我最近才开始学习Spring框架。在我的控制器中,我写 @GetMapping("/users/{username}") public String getUserByUsername(@PathVariable(value = "username") String username, ModelMap model) { User founduser = userRepository.findById(username) .orElseThrow(() ->

我最近才开始学习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";
}
然后,我尝试获取model属性并在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>

${one.username}
${one.createdAt}
但是,我发现test=“${not empty founduser}始终为false,这意味着我的founduser属性为null。调试时,它显示模型成功添加了founduser


谁能告诉我出错的原因?非常感谢!

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

但是,您可以使用
重定向:/profile
来显示JSP。重定向意味着将向服务器发送另一个新请求。此新请求不会经过
getUserByUsername
控制器,因此此新请求属性中没有
founduser
,JSP无法找到它

要解决这个问题,根据您的应用程序体系结构,您可以

  • 不要在控制器中重定向,只需返回
    profile

  • 如果确实需要重定向,请将这些值添加到flash属性中,以便在重定向后仍能保留并访问这些值:

    model.addFlashAttribute(“founduser”,founduser);


  • 非常感谢你!