How to insert data using spring mvc and angularJS -
i want insert data database using angularjs , spring mvc, according tutorial did failed insert data database.
controller :
@requestmapping(value = "/add", method = requestmethod.post) public @responsebody string addemployee(@modelattribute(value="employee")employeeentity employee, bindingresult result) { employeemanager.addemployee(employee); return "redirect:/"; }
jscode :
$scope.insertdata = function(){ $http.post("http://localhost:9090/crudoperations/add", {"firstname":$scope.firstname}) .success(function(data,status,header,config) { console.log("inserted"); }); }
jsp:
<form:form class="form-horizontal" role="form" method="post" commandname="employee"> <div class="form-group col-lg-7" > <label for="email" class="control-label">first name:</label> <input type="text" ng-model="firstname" class="form-control" placeholder="enter firstname"/> </div> <div class="form-group col-lg-7"> <button type="submit" ng-click="insertdata()" class="btn btn-primary">submit</button> </div>
you didn't specify problem , behaviour experiencing, there seems problems code can pointed out.
it seems trying mix 2 ways of communicating backend - more traditional, form based approach, , rest api.
annotating controller method @responsebody means, spring should not try resolve view render. should instead convert object has been returned method using message converter (usually - serialize json) , send result client in response body. used expose rest endpoint.
that means returning string "redirect:/" not cause redirect. instead string returned in body.
it better return persisted entity returned employeemanager.addemployee(employee)
if process of persisting causes id set. way client can receive id , find employee later.
if passing data angular backend using json should use @requestbody annotation instead of @modelattribute. in turn cause object deserialized. did not show employeeentity class, don't know if want.
on client side don't need form element. angular can pass data using ajax calls. having form , submit button cause browser reload page , not want if creating single page application.
Comments
Post a Comment