【问题标题】:Model Boolean attribute value not showing in HTML (Spring MVC)模型布尔属性值未在 HTML 中显示(Spring MVC)
【发布时间】:2017-02-21 12:20:19
【问题描述】:

控制器:

@RequestMapping("/approveRequestById")
    public String approveRequestById(Principal principal, @RequestParam(value="id") String requestId, Model model) {
        Users manager = usersRepository.findOneByInitialName(principal.getName());
        RequestDO request = requestRepository.findOne(Long.parseLong(requestId));
        requestRepository.updateRequestStatusByRequestId(RequestStatus.APPROVED, request.getId());
        Users employee = usersRepository.findOne(request.getUsers().getId());
        // Instead of getting the same RequestDO object from DB, I just updated it's status for using in mail correctly.
        request.setStatus(RequestStatus.APPROVED);

        model.addAttribute("requestFlag", true);
        log.info("Model: " + String.valueOf(model));

        /***
         Send Notification Mail to Employee
         ***/
        mailUtil.sendNotificationEmailWithTemplating(employee, manager, request);

        return "redirect:/requests";
    }

HTML:

<th:block th:switch="${requestFlag}">
                    <th:block th:case="true">
                        <div style="width: 100%; height: 30px; color: #fff; background: #C00000; text-align: center; padding: 10px;"><span
                                style="font-weight: bold; padding-bottom: 10px; ">The request from your mailbox has been approved!</span></div><br>
                    </th:block>
                </th:block>

在邮件链接后登陆页面时的日志输出:

Model: {currentRole=EMPLOYEE, numRequests=0, requestFlag=true}

用户通过电子邮件墨水访问页面,即http://localhost:8181/request/approveRequestById?id=2。在此页面上,控制器插入模型属性requestFlag 并将其设置为true。我可以在日志和调试模式下看到,模型在调用请求映射时确实将此属性添加到模型中,即/request/approveRequestById

我的问题是逻辑在前端不起作用。 div 不显示。如果有一个 requestFlag 等于 true,它应该显示一个 div。我可以使用&lt;th:block th:text="@{requestFlag}"&gt;Request Flag&lt;/th:block&gt; 打印该值,但它没有给我想要的布尔值。布尔值不能通过 Thymeleaf 呈现吗?包含模型中的其他字符串打印得很好。在模板的呈现顺序方面,我是否遗漏了一些基本的东西?非常感谢所有帮助。

【问题讨论】:

  • 尝试使用RedirectAttributes 而不是Model
  • 模型的范围不适用于模型。你可以比较一下 servlet 中的 httprequest.forward VS httprequest.sendRedirect。

标签: java spring spring-boot model controller


【解决方案1】:

由于您使用的是redirect:,因此您的model 将因重定向而丢失(将创建一个新请求),因此您必须将数据存储在redirectAttributes

@RequestMapping("/approveRequestById")
public String approveRequestById(Principal principal, @RequestParam(value="id") String requestId, Model model, RedirectAttributes redirectAttributes) {

        //use this
        redirectAttributes.addFlashAttribute("requestFlag", true);

        //instead of
        model.addAttribute("requestFlag", true);

        return "redirect:/requests";
    }

【讨论】:

  • 这很有效,谢谢!有点像将 Intent Extras 传递给 Android 中的活动......
猜你喜欢
  • 2013-06-01
  • 2013-08-27
  • 2013-12-18
  • 2021-03-14
  • 2013-03-23
  • 2013-10-09
  • 1970-01-01
  • 2017-02-11
  • 2021-03-08
相关资源
最近更新 更多