使用JSTL检查弹簧绑定错误

Mar*_*ada 6 spring-mvc

我已经尝试了一段时间,但找不到合适的解决方案.

我想使用JSTL来检查我的Spring MVC 2.5中是否存在任何绑定错误(字段错误或全局错误).

我知道我可以使用这段代码:

<p>
    <spring:hasBindErrors name="searchItems">
        An Error has occured
    </spring:hasBindErrors>
</p>
Run Code Online (Sandbox Code Playgroud)

但我想利用JSTL来检查是否有任何错误.

我使用JSTL尝试过这个:

<c:if test="${not empty errors}">
    An Error has occured
</c:if>
Run Code Online (Sandbox Code Playgroud)

但似乎我无法正确捕捉它.

我需要使用JSTL,因为JSP的其他部分依赖于是否存在绑定错误.

Art*_*ald 6

如上所述

我想利用JSTL来检查是否有任何错误

只是使用(它只适用于Spring MVC 2.5 - 对于Spring MVC 3.0不可移植,尽管我认为它是requestScope ['bindingResult.<COMMAND_NAME_GOES_HERE> .allErrors'])

<c:if test="${not empty requestScope['org.springframework.validation.BindingResult.<COMMAND_NAME_GOES_HERE>'].allErrors}">
    An Error has occured!!!
</c:if>
Run Code Online (Sandbox Code Playgroud)

请记住,默认命令名称是非限定命令类名称,第一个字母是小写的.注意下面的命令名称是pet

private PetValidator petValidator = new PetValidator();

@RequestMapping(method.RequestMethod.POST)
public void form(Pet command, BindingResult bindingResult) {
    if(petValidator.validate(command, bindingResult)) {
        // something goes wrong
    } else {
        // ok, go ahead
    }
}
Run Code Online (Sandbox Code Playgroud)

所以你的表格应该是这样的

<!--Spring MVC 3.0 form Taglib-->
<form:form modelAttribute="pet">

</form:form>
<!--Spring MVC 2.5 form Taglib-->
<form:form commandName="pet">

</form:form>
Run Code Online (Sandbox Code Playgroud)

除非你使用@ModelAttribute

@RequestMapping(method.RequestMethod.POST)
public void form(@ModelAttribute("command") Pet command, BindingResult bindingResult) {
    // same approach shown above
}
Run Code Online (Sandbox Code Playgroud)

这样,您的表单应该是这样的

<!--Spring MVC 3.0 form Taglib-->
<form:form modelAttribute="command">

</form:form>
<!--Spring MVC 2.5 form Taglib-->
<form:form commandName="command">

</form:form>
Run Code Online (Sandbox Code Playgroud)


小智 6

像这样的东西:

<spring:hasBindErrors name="userName">
    <c:set var="userNameHasError" value="true" />
</spring:hasBindErrors>

<c:choose>
    <c:when test="${userNameHasError}">
         <%-- Display username as textbox --%>
    </c:when>
    <c:otherwise>
         <%-- Display username as label --%>
    </c:otherwise>
</c:choose>
Run Code Online (Sandbox Code Playgroud)

您也许还可以设置错误以捕获页面上的所有错误(未经测试):

<spring:hasBindErrors name="*">
    <c:set var="userNameHasError" value="true" />
</spring:hasBindErrors>
Run Code Online (Sandbox Code Playgroud)

享受!