java - Spring form ModelAttribute field validation to avoid 400 Bad Request Error -
i've got articleformmodel
containing data sent normal html form
injected spring using @modelattribute
annotation, i.e.
@requestmapping(value="edit", method=requestmethod.post) public modelandview acceptedit(@modelattribute articleformmodel model, httpservletrequest request, bindingresult errors) { //irrelevant stuff }
everything works fine point. problem articleformmodel
contains double
field (protected
, set using normal setter). works fine long data sent user number. when type word, 400 bad request http error
.
i've registered webdatabinder
controller
@initbinder protected void initbinder(webdatabinder binder) throws servletexception { binder.setvalidator(validator); }
where validator
instance of custom class implementing org.springframework.validation.validator
interface don't know next. i'd able parse model, valid http response , display error message in form. initbinder()
method called , can call validator.validate()
doesn't change error (for wrong data).
i'm aware use setter parse string, check if it's number, if not, store info in variable, retrieve variable during validation, seems work. there has easier way force type on field without getting error. also, issue in data binding, not validation, feel should placed in respective code layer.
i thinking implementing java.beans.propertyeditor
, calling binder.registercustomeditor()
, i'm lacking reliable knowledge source.
client-side validation (checking if data number via javascript) isn't possibility.
tl;dr:
how can force field of specific type @modelattribute
item without getting 400 bad request http error
?
you can use <form:errors>
binding error.
it looks this:
controller:
@requestmapping(value="edit", method=requestmethod.post) public modelandview acceptedit(@modelattribute articleformmodel model, bindingresult errors, httpservletrequest request) { if (errors.haserrors()) { // error handling code goes here. } ... }
errors
parameter needed placed on right after model.
see below details (example 17.1):
jsp:
<form:form modelattribute="articleformmodel" ... > ... <form:errors path="price" /> </form:form>
message properties file:
typemismatch.articleformmodel.price=customized error message
Comments
Post a Comment