Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring MVC Error Messages

Spring MVC Error Messages

Hello, Spring Fellows,

I have a form that is validated by the Spring Validation once submitted. Each field on the form may contain multiple errors messages if validation fails, so error messages are displayed below the field, not next to it. Here's the code snippet.

<tr>
    <td><form:input path="name" /></td>
</tr>
<tr>
    <td>
        <form:errors path="name*" />
    </td>
</tr>

Note that there is a star at the end of the path value to indicate that all error messages for the name must be displayed.

As you can see, the problem is that, if there is no error message, there will be an extra row on the page that looks out of place to the user. The code above is an overly simplied version, so the actual code has a lot more stuff in it, which prevents me from moving the <form:errors> tag inside the tag containing the field.

Is there a way to find out if there is any message associated to a given path on the JSP level? Basically, I would like to do the following:

<c:if test="${what do I write here?}">
    <tr>
        <td>
            <form:errors path="name*" />
        </td>
    </tr>
</c:if>

Thanks!

like image 654
Tom Tucker Avatar asked Nov 22 '10 19:11

Tom Tucker


People also ask

How does Spring MVC handle 404 error?

The 404 error code is configured properly, but it will caused the “. htm” extension handling conflict between the “servlet container” and Spring's “DispatcherServlet“. To solve it, try change the 404. htm to other file extension, for example 404.

What is the use of BindingResult in Spring MVC?

Interface BindingResult. General interface that represents binding results. Extends the interface for error registration capabilities, allowing for a Validator to be applied, and adds binding-specific analysis and model building. Serves as result holder for a DataBinder , obtained via the DataBinder.


2 Answers

You can do something like this (notice that bind is from spring taglib):

<spring:bind path = "name*">
    <c:if test="${status.error}"> 
        <tr> 
            <td> 
                <form:errors path="name*" /> 
            </td> 
        </tr> 
    </c:if> 
</spring:bind>
like image 92
axtavt Avatar answered Oct 14 '22 15:10

axtavt


I solved your problem by doing this:

<table>
    <form:errors path="firstName">
    <tr>
        <td colspan="2">
            <form:errors path="firstName"/>
        </td>
    </tr>
    </form:errors>
    <tr>
        <td><form:label path="firstName"><spring:message code="helloworld.label.firstName"/></form:label></td>
        <td><form:input path="firstName"/></td>
    </tr>
</table>

errors tag body will be evaluated only if there are errors on the path.

like image 36
Alfredo Osorio Avatar answered Oct 14 '22 16:10

Alfredo Osorio