2015-01-10 204 views
0
全球錯誤結果檢查

要顯示與Spring MVC與百里香葉創建全局錯誤,我試圖在http://www.thymeleaf.org/doc/tutorials/2.1/thymeleafspring.html#global-errors給出的例子:春百里香葉在NPE

也就是說,是:

<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"; 
} 

回答

3

解決:

th:object需要在標籤之前全球錯誤檢查。不幸的是,這在春季百里香葉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> 

..其中「命令」是控制器的形式bean的名字。

This thread幫我弄明白了。

+0

通過使用語法'th:errors =「$ {command.global}」',您應該可以在表單外部或者在沒有'th:object =「$ {command}」''的情況下訪問它。見[http://www.thymeleaf.org/doc/tutorials/2.1/thymeleafspring.html#displaying-errors-outside-forms] – phn