【发布时间】:2017-03-17 14:22:44
【问题描述】:
在 Validator 类的实现中验证日期间隔的重叠。我从 Posgresql 数据库中得到一个列表,我想在错误消息旁边显示该列表。
我尝试用这行代码插入它,但没有成功:
model.addAttribute("dateOverlaps", pricesValidator.getDBIntervals());
这是完整的代码:
@Controller
public class PricesController {
@Autowired
private RateRepository rateRepository;
@Autowired
private PricesValidator pricesValidator;
@InitBinder
protected void initBinder(WebDataBinder binder) {
binder.addValidators(pricesValidator);
}
//Enter new price form
@GetMapping("/admin/rates/priceform")
public String priceForm(Model model){
model.addAttribute("rate", new Rate());
model.addAttribute("dateOverlaps", pricesValidator.getDBIntervals());
return "/admin/rates/priceform";
}
@PostMapping("/admin/rates/priceform")
public String priceSubmit(@ModelAttribute @Valid Rate price, BindingResult bindingResult){
if(bindingResult.hasErrors()){
return "/admin/rates/priceform";
}
rateRepository.addRate(price);
return "redirect:/admin/rates/prices";
}
}
我使用 Thymeleaf,但我想当然地认为问题不在于查看器。
这是 html 视图:
<!--Global validation results-->
<div th:if="${#fields.hasErrors('global')}">
<div class="alert alert-danger" role="alert"
th:each="err : ${#fields.errors('global')}">
<div th:switch="${err}">
<p th:case="error.fromAfterTo" th:text="#error.fromAfterTo}"></p>
<p th:case="error.overlaps" th:text="#{error.overlaps}"></p>
<ul>
<li th:text="#{from} + ' - ' + #{to}"></li>
<li th:each="interval : ${dateOverlaps}"
th:text="${#temporals.format(interval.datefrom, 'dd/MM/yyyy')} + '-' +
${#temporals.format(interval.dateto, 'dd/MM/yyyy')}">Intervals</li>
</ul>
</div>
</div>
</div><!--Global validation results-->
提前感谢您的帮助。
【问题讨论】:
-
如何尝试获取视图中的值?
-
那么当你调用端点时你究竟得到了什么?
-
我已添加视图。 @DanielOlszewski
-
我收到带有 #{error.overlaps} 文本的错误消息,但没有间隔列表的符号。验证器工作。 @zakariaamine
-
你在做什么,你期望发生什么,反而会发生什么?你调试过你的代码吗?打印 priceValidator.getDBIntervals() 返回的内容。查看生成的 HTML?我对百里香一无所知,但 ul 在开关内,但不在任何情况下。正常吗?显示的是第一个 li 吗?
标签: spring spring-boot thymeleaf