I am trying to get model validation working with my spring boot mvc application. I am using freemarker as view templates. My problem is now that even though model validation works as expected the model errors are not shown in my view.
Here is some example code. The Model:
public class TestModel {
@Size(min=2, max=10)
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
The Controller
@Controller
@RequestMapping("/test")
public class OrderController extends BaseController {
@RequestMapping(value = "new/greenhouse", method = RequestMethod.GET)
public String get(@ModelAttribute TestModel testModel) {
testModel.setName("Hello world");
return "test.ftl";
}
@RequestMapping(value = "/test", method = RequestMethod.POST)
public String post(@ModelAttribute @Valid TestModel testModel, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
// The bindingResult contains the "correct" errors
return "test.ftl";
}
return "redirect:/";
}
}
The view:
<#import "../layout.ftl" as layout />
<#import "/spring.ftl" as spring />
<#import "../freemarker.ftl" as ftl />
<@layout.defaultLayout>
<form action="/test" method="post">
<@ftl.csrfToken />
Name:
<@spring.formInput "testModel.Name" />
<@spring.showErrors "<br>" /> <#-- Does not print the error as status.errorMessages is not populated -->
<#-- This will at least display the default Message -->
<#list spring.status.errors.allErrors as error>
<span class="has-error">${error.defaultMessage} </span>
</#list>
</form>
</@layout.defaultLayout>
Any idea why status.errorMessages
does not get populated?
So I finally found the solution to this:
The property name in the Freemarker view has to be lowercase (as is the private member name in the model class). The correct view would look like this:
<@spring.formInput "testModel.name" />
<@spring.showErrors "<br>" />