【问题标题】:Spring Thyme Leaf checking for global errors results in NPESpring Thyme Leaf 检查全局错误导致 NPE
【发布时间】:2015-03-09 00:34:57
【问题描述】:

为了显示使用带有 Thyme Leaf 的 Spring MVC 创建的全局错误,我尝试了http://www.thymeleaf.org/doc/tutorials/2.1/thymeleafspring.html#global-errors 中给出的示例:

那个,是:

<div th:if="${#fields.hasGlobalErrors()}">

<ul th:if="${#fields.hasErrors('global')}">

<div th:if="${#fields.hasGlobalErrors()}">

当我将它们添加到我的 HTML 时,页面甚至不会呈现,更不用说提交表单了。所有示例都导致:

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.thymeleaf.exceptions.TemplateProcessingException: Exception evaluating SpringEL expression: "#fields.hasErrors('global')"

我在 v2.1.4 和 v.2.1.3 上试过这个,得到了同样的错误。错误还是我做错了什么?

是的,标签都是封闭的并且格式正确。是的,这段代码在一个表单中。是的,表单的所有其他方面都可以在没有全局错误检查的情况下工作。

以下是损坏的 HTML 的简短版本:

<form action="search.html" th:action="@{/auto/search}">
<p th:if="${#fields.hasErrors('global')}" th:errors="*{global}">
    Incorrect date
</p>
<input type="text" th:field="${command.stockNumber}" />
<select th:field="*{command.startYear}">
    <option value="" th:each="year : ${modelYears}" th:value="${year}"
            th:text="${year}"></option>
</select>
</form>

还有控制器..

@RequestMapping(value = "/auto/search", method = RequestMethod.POST)
public String search(@Validated
                     @ModelAttribute("command")
                     AutoSearchCommand autoSearchCommand
                     BindingResult result, Model model) {
    return "search";
}

【问题讨论】:

    标签: spring thymeleaf


    【解决方案1】:

    已解决:

    th:object 需要在全局错误检查之前的标记中。不幸的是,Spring Thyme Leaf tutorial 中没有提到这一点。据推测,我在控制器中覆盖了某个默认表单名称。

    在这个工作的 html 中添加标签:

    <form action="search.html" th:action="@{/auto/search}">
    <div th:object="${command}" th:remove="tag">
        <p th:if="${#fields.hasErrors('global')}" th:errors="*{global}">
            Incorrect date
        </p>
    </div>
    <input type="text" th:field="${command.stockNumber}" />
    <select th:field="*{command.startYear}">
        <option value="" th:each="year : ${modelYears}" th:value="${year}"
                th:text="${year}"></option>
    </select>
    </form>
    

    .. 其中“command”是控制器中表单 bean 的名称。

    This thread 帮我弄明白了。

    【讨论】:

    猜你喜欢
    • 2015-02-12
    • 1970-01-01
    • 2012-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-23
    • 1970-01-01
    相关资源
    最近更新 更多