模型布尔属性值未在HTML中显示(Spring MVC)

时间:2017-02-21 12:20:19

标签: java spring spring-boot model controller

控制器:

@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。我可以使用<th:block th:text="@{requestFlag}">Request Flag</th:block>打印该值,但它并没有给我我想要的布尔值。 Booleans不能通过Thymeleaf呈现吗?包含的模型中的其他字符串打印得很好。我是否遗漏了模板渲染顺序的基本内容?所有人都非常感谢。

1 个答案:

答案 0 :(得分: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";
    }