Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between spring:bind and form:errors?

I have following form in Spring that is showing error messages. I am wondering when should I use spring:bind? What does that do that differentiate that with ? I studied these pages a,b but I am still puzzled.

1

<form:form method="post"
    action="http://localhost:8080/project/calculator/process"
    modelAttribute="keyPadForm">
        Name1: <form:input type="text" path="name1" />
        <form:errors path="name1" />

2

<form:form method="post"
    action="http://localhost:8080/project/calculator/process"
    modelAttribute="keyPadForm">
    <spring:bind path="name1">
        Name1: <form:input type="text" path="name1" />
        <form:errors path="name1" />
    </spring:bind>
like image 276
Jack Avatar asked Sep 26 '15 08:09

Jack


2 Answers

With spring:bind, you can use ${status.error} to check if the name1 field has an error, and display different CSS class conditionally.
The error message is still displayed via form:errors, but this way you get more controls.
for example:

<form:form method="post" modelAttribute="userForm" action="${userActionUrl}">
    <spring:bind path="name">
    <div class="form-group ${status.error ? 'has-error' : ''}">
        <label>Name</label>
        <form:input path="name" type="text" id="name" />
        <form:errors path="name" />
    </div>
    </spring:bind>
</form:form>

and you can refer to this Spring MVC Form – Check if a field has an error

like image 51
Vito Avatar answered Oct 20 '22 10:10

Vito


In your second case, spring:bind tag is obsolete, your first form

<form:form method="post"
    action="http://localhost:8080/project/calculator/process"
    modelAttribute="keyPadForm">
        Name1: <form:input type="text" path="name1" />
        <form:errors path="name1" />

is a sort of syntactic sugar, and the equivalent without using the form tag library, rather only the common HTML form tags, would be based on spring:bind and would look something like:

<spring:nestedPath path="keyPadForm">
   <form method="post" action="http://localhost:8080/project/calculator/process">
    <spring:bind path="name1">
        Name1:<input type="text" name="${status.expression}" value="${status.value}">
       <span class="fieldError">${status.errorMessage}</span>
    </spring:bind>
   </form>
</spring:nestedPath>

There are scenarios where you can make a difference, e.g. form:input is always a two way bind, so the value is sent to the server and the current value displayed, where as with spring:bind you can achieve a one way bind, only sending to server, by omitting the value e.g. <input type="text" name="${status.expression}">, but the main gist is that form tag library provides a more convenient bind related tags

like image 25
Master Slave Avatar answered Oct 20 '22 10:10

Master Slave