Ajax Post containing list of objects to Spring MVC Controller - arrays

How do i post a list of objects from javascript to Spring MVC Controller? I can post arrays, objects, but not a combination of the 2. This is my code below.
Javascript:
var utilData = getTableData();
// Sending data over to server
console.log(utilData);
$.ajax({
url: "saveUtilData2.html",
type: "POST",
contentType: "application/json",
dataType: "json",
data: {utilArray: utilData},
success: function(data){
alert("save was sucessful");
},
error: function(){
alert("Save wasn't successful");
}
});
Spring Controller (tried changing utilData to String[] and object[] ... both didnt work:
#RequestMapping(value="/saveUtilData2.html", method=RequestMethod.POST)
public ModelAndView saveUtilData2(#RequestParam("utilArray") String[] utilData, HttpServletRequest request)
{
System.out.println("Util Save Data method 2");
ModelAndView mv = new ModelAndView("util");
return mv;
}

Use #Requestbody instead of Requestparam

Related

how to send json data by $http.Post from Angular to webAPI POST method?

I am trying to pass data as JSON object by $http.Post to webAPI method. In WebAPI method, the parameter of the method is a class object.
It works fine when I test the webAPI method by Postman.But I am not able to pass the JSON object by angular $http.post method-I get null values in the webAPI parameter(in the class object).
Can someone please advise how to fix the issue.i am new to AngularJS.Kindly help.
AngularJS Code
angular.module('Test.Employer')
.controller('EmployerController', ['$scope','headerValue', '$http',
function ($scope, headerValue, $http) {
var ipEmployerDetls = {
EmployerName: "cherokee",
Company: "ABC"
};
$http({
url: "http://localhost:212122/api/Values/PostEmployeeData",
dataType: 'json',
method: 'POST',
data: JSON.stringify(ipEmployerDetls),
headers: {
"Content-Type": "application/json"
}
}).success(function (response) {
$scope.object = response.data;
})
.error(function (error) {
alert(error.Message);
});
})();
WebAPI
using System.Web.Http;
using AttributeRouting.Web.Http;
namespace webAPITestProject.Controllers
{
[Route("api/Values")]
public class ValuesController : ApiController
{
retrieveEmployeeData empData = new retrieveEmployeeData();
retrieveProductDetails prodDetls = new retrieveProductDetails();
[Route("PostEmployeeData")]
[HttpPost]
public DataTable PostEmployeeData([FromBody] Employer empDetails)
{
DataTable dataTable = new DataTable { TableName = "MyTableName" };
dataTable = empData.getEmployeeData(empDetails);
return dataTable;
}
}
}
NOTE: I get NULL value in empDetails in webAPI method,but when I test the method in Postman,it has value.
Your routing attributes don't look right for how you've specified your $http API call.
Looks like you want the class-level attribute to be:
[RoutePrefix("api/Values")]
public class ValuesController : ApiController
Which will mean that PostEmployeeData has a route of api/Values/PostEmployeeData.
You'll also need to ensure that your properties in ipEmployerDetls directly map to your Employer class (which you haven't shown), so that model binding works correctly.

angular POST not working with servlet

I am trying to use angularjs POST (or even GET) to a servlet with the following:
var json = { hello: "world" }
var deffered = $q.defer();
$http({
method: "POST",
url: url,
headers: { "Content-Type" : "application/json" },
request: JSON.stringify(json)
}).then(data) {
if(data.data) {
deferred.resolve({
response : data
});
)
})
return deffered.promise;
within the servlet, simple:
String val = request.getParameter("request")
it never seems to see it
I have tried:
data: JSON.stringify({ request: json })
data: { request: json }
"request" : JSON.stringify(json)
etc
if I comment out the getParameter and just return a generic value using Gson
JsonObject json = new JsonObject();
json.addProperty("This", "works");
response.getWriter().print(new Gson().toJson(json));
that comes back fine so is there something within the angular POST I am doing wrong here? I have also tried using "GET" instead but same result.
EDIT: I would like to understand POST method and the "proper" way to get the data from the json object if getParameter is wrong please~
getParameter() returns http request parameters, you should add this params by using :
params: JSON.stringify(json)
Not with
request: JSON.stringify(json)
Take a look in params in get and params in post.

Getting JsonArray data from Jersey using Angular js

I am writing simple application with REST in the backend and Angular as frontend. And now I cant make them talk properly.
My Jersey class gets some data from database make JSONArray from it and send it to response to get.
#GET
#Path("{userID}")
#Produces(MediaType.APPLICATION_JSON)
public String getLearningList(#PathParam("userID") int userId)
{
SqlConnector con = new SqlConnector();
List<String> list = con.getUsersLearningList(userId);
JSONObject jObj = new JSONObject();
jObj.put("list", list);
JSONArray jArray = jObj.getJSONArray("list");
return jArray.toString();
}
In Angular I am using angular-resourse to get data from REST and even I made isArray: true I am getting this error:
Error in resource configuration for action `get`. Expected response to contain an object but got an array
Here is my angular
myApp.factory('GetDataService', ['$resource', function($resource){
return {
getData: function(url)
{
return $resource(url,{},{
query: {
method: 'GET',
params: {},
isArray: true
}
})
}
}
}]);
SqlConnector is just my class which work with database.
I am completely new in Angular. Thank you in advance!

How to send Multipart data and json object from ajax to spring

I have done a poc to upload(drag&drop) file from angular js by sending multi part request to controller(Sprig), but i need to send some more parameters along with file(Multi part content) can any one suggest me to post file(Multi part content) and json object to controller.
You can't do both just in one method. If it's a big object I suggest to create another method and call it after or before file upload. Otherwise for e.g. if you have HTML form you can do something like this:
var form = new FormData(document.getElementById('file-upload-form'));
$.ajax({
url: /file/upload,
data: form,
dataType: 'text',
processData: false,
contentType: false,
type: 'POST',
success: function () {
//Do something
},
error: function (jqXHR) {
//Do something
}
});
Then in your Spring controller:
#RequestMapping(value = "/file/upload", method = RequestMethod.POST)
#ResponseBody
public ResponseEntity uploadFile(MultipartHttpServletRequest request) {
Iterator<String> itr = request.getFileNames();
MultipartFile file;
try {
file = request.getFile(itr.next()); //Get the file.
} catch (NoSuchElementException e) {
}
String param = request.getParamterer("paramName"); //Get your parameters
//Do something else.
}
You have to declare MultipartHttpServletRequest which will contain the file and all form data of your request.
Hope this helps.

Bad Request Error while sending json data to spring mvc controller

I am trying to send some json data from angular ng grid to spring mvc controller,but i am getting error as 400 (Bad request) The request sent by the client was syntactically incorrect. .
This is my Request Paylod:
[{"orderId":1,"orderTitle":"Xcel","orderDetail":"cash","orderType":"Xcel","orderPriority":"22.0","retailerId":0,"orderRefno":"9.900499743E9","customerName":"high","customerContactno":"pen drive","customerEmailId":"nutral","paymentType":"iffu#gmail.com","orderStatus":"pen drive","reciptDate":null,"bayNumber":"Xcel","deliveredDate":null,"deliveredBy":"Irfan","updatedOn":null,"pudoOutlet":null,"retailer":null,"outletId":0}]
here is my spring mvc controller:
#RequestMapping(value="/createorder",method=RequestMethod.POST,headers="Content-Type=application/json")
public #ResponseBody ModelAndView createOrder(#RequestBody Order order){
System.out.println("hiiiii"+order);
try{
orderDao.createOrder(order);
return new ModelAndView("product1.html");
}
catch(Exception e)
{
System.out.println(e);
}
return new ModelAndView("pr.html");
}
here is my angular controller from where i am posting:
$scope.save = function() {
console.log("hii inside save function");
console.log($scope.mySelections);
console.log("after myselection")
var d=$scope.mySelections;
console.log("hhhhh" +d);
$http({
method: 'POST',
url: './createorder',
headers: {'Content-Type': 'application/json'},
data:d
}).success(function (data)
{
$scope.status=data;
});
};
I am totally confused why i am getting this error ? Is it because i am sending some null values to spring mvc controller ? if yes how to solve this issue ?
Is Order an inner class? If so, try taking that class into its own file. Worked for me.

Resources