【问题标题】:Spring: How to get the model attribute and check if it is null in JSP?Spring:如何在JSP中获取模型属性并检查它是否为空?
【发布时间】:2019-02-23 07:00:32
【问题描述】:

我最近才开始学习 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成功。

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

【问题讨论】:

    标签: spring spring-boot jsp jstl


    【解决方案1】:

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

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

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

    1. 不要在你的控制器中重定向,只返回profile

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

      model.addFlashAttribute("founduser",founduser);

    【讨论】:

    • 非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2011-02-01
    • 2020-06-29
    • 1970-01-01
    • 2019-01-03
    • 2013-12-22
    • 1970-01-01
    • 1970-01-01
    • 2017-12-12
    相关资源
    最近更新 更多