How can I avoid having too many arguments in Spring Java controllor -
in spring web application:
@requestmapping(value = new) public string addproduct(@requestparam string name, @requestparam(required = false) string description, @requestparam string price, @requestparam string company, modelmap model, @requestparam(required = false) string volume, @requestparam(required = false) string weight) { try { productmanagementservice.addnewproduct(name, description, company, price, volume, weight); model.addattribute("confirm", product_added); return form_page; } catch (numberformatexception e) { logger.log(level.severe, invalid_value); model.addattribute("error", invalid_value); return form_page; } catch (invaliduserinputexception e) { logger.log(level.severe, e.getmessage()); model.addattribute("error", e.getmessage()); return form_page; } }
what possible ways reduce/bind total number of arguments.
create form class i.e
class myform{ string name; string price; string description; ... // getters , setters included }
and like
@requestmapping(value = new) public string addproduct(@modelattribute myform myform)
instantiation of myform
, binding of request parameters properties , adding modelmap done spring behind scenes.
source: spring docs
an @modelattribute on method argument indicates argument should retrieved model. if not present in model, argument should instantiated first , added model. once present in model, argument's fields should populated request parameters have matching names. known data binding in spring mvc, useful mechanism saves having parse each form field individually.
Comments
Post a Comment