Passing in JSON array to spring MVC Controller - json

I am trying to pass a JSON array into spring MVC Controller like such:
var myList = new Array();
data._children.forEach( function (d) {
myList.push( {NAME: d.name, TYPE: d.TYPE, FDATE: d.FDATE } );
});
$.post("/ListRequest", {myList: myList});
The controller looks as such:
#RequestMapping(value="/ListRequest", method = RequestMethod.POST)
public void ListRequest(#RequestParam("myList") myList tempmyList )
{
System.out.println(tempmyList);
}
The class myList defined as such:
public class MyList {
private List<ListT> ListT;
public List<ListT> getListT() {
return ListT;
}
public void setListT(List<ListT> listT) {
ListT = listT;
}
}
ListT class:
public class ListT {
private String NAME;
private String TYPE;
private Long FDATE; ...
I keep getting this error:
HTTP Status 400 - Required myList parameter 'myList' is not present
Also tried this request:
$.ajax({
type: "post",
url: "ListRequest", //your valid url
contentType: "application/json", //this is required for spring 3 - ajax to work (at least for me)
data: JSON.stringify(myList), //json object or array of json objects
success: function(result) {
//do nothing
},
error: function(e){
alert('failure');
}
but get this error: JBWEB000120: The request sent by the client was syntactically incorrect.

try to add this to you ajax call it should fix the unsupported response :
headers : {
'Accept' : 'application/json',
'Content-Type' : 'application/json'
},
this is a full example of ajax call that is working for me :
$.ajax({
dataType : "json",
url : this.baseurl + "/dataList",
headers : {
'Accept' : 'application/json',
'Content-Type' : 'application/json'
},
data : JSON.stringify(params),
type : 'POST',
success : function(data) {
self.displayResults(data);
},
error : function(jqXHR,textStatus,errorThrown ){
showPopupError('Error','error : ' + textStatus, 'ok');
}
});

Even I was facing same problem.
My client request was right and generated proper json file.
but still i was getting same error.
I solved this error using #JsonIgnoreProperties(ignoreUnknown = true) in pojo class.
refer this link.
Spring MVC : The request sent by the client was syntactically incorrect

You can try
#RequestParam("myList") myList tempmyList
#Param myList tempmyList
in addition, class names must begin with a capital letter.

Related

Spring Rest Controller POST request doesn't work with Ajax Json Array payload

I am getting 404 not found error while sending post request with json payload . At backend I am using spring rest controller .
Please find the code below .
#RequestMapping(value = "/api/testEnvironment/update", method = RequestMethod.POST , consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<?> updateEnvironment(#RequestParam("ids") String[] ids, #RequestParam("name") String name) {
System.out.println(ids);
return new ResponseEntity<>(HttpStatus.OK);
}
And Jquery function for above rest controller :-
function testing(){
var a = [] ;
a.push('a');
a.push('b');
var b = '23';
var search = {
"ids" : a,
"name" : b
}
$.ajax({
type : "POST",
url : "api/testEnvironment/update",
contentType: "application/json",
data: JSON.stringify(search),
traditional: true,
success : function(data) {
},
error : function(e) {
}
});
}

How to send array of json objects to spring controller using ajax

I have converted all tables into json format using the below code:
var table2 = $('#yTable').tableToJSON();
alert(JSON.stringify(table2));
How do I send these three json arrays to spring controller? In spring controller I want these json array of objects as separate params:
[
{"Label":"A","Dimension":"0"},
{"Label":"B","Dimension":"10"},
{"Label":"C","Dimension":"20"},
{"Label":"D","Dimension":"30"},
{"Label":"E","Dimension":"40"}
]
[
{"Label":"1","Dimension":"0"},
{"Label":"2","Dimension":"10"},
{"Label":"3","Dimension":"20"},
{"Label":"4","Dimension":"30"},
{"Label":"5","Dimension":"40"}]
[
{"Label":"Floor1","Dimension":"0"},
{"Label":"Floor2","Dimension":"10"},
{"Label":"Floor3","Dimension":"20"},
{"Label":"Floor4","Dimension":"30"},
{"Label":"Floor5","Dimension":"40"}
]
ajax call
$.ajax({
type: "POST",
contentType : 'application/json; charset=utf-8',
dataType : 'json',
url: "/bimspring/gridData",
data: JSON.stringify(postData),
success : function(response) {
// do something ...
},
error : function(e) {
alert('Error: ' + e);
}
});
Controller
#RequestMapping(value = "/gridData", method = RequestMethod.POST)
public #ResponseBody String getSearchUserProfiles(#RequestBody Search[] list) {
return null;
}

Return json array from client to spring controller

I need to send data from the client html back to the spring controller.
I have a controller which generates a Json array whichh I sent via ajax to the html side when requested.
That functions well.
The Problem is I need to send the Json array back to another controller for evaluation and changes.
If I post the data and assign an class object of the original class I get the error " Bad request" and it didn't work.
If I assign an object in the controller which consumes the post. That works
but I get an hashmap for which I dont know how to access.
I cant cast it to another class nor access it to work with it.
Since I am new to this can someone give me an advice how to consume the post
on the receiving controller side.
Thanks
Khelvan.
Controller code ist stated below
controller 1 for Get
#RequestMapping("/Person")
#ResponseBody
public ArrayList<Person> ajax_Person_array()
{
ArrayList<Person> Dummy = new ArrayList<Person>();
for ( x=0; x < 5; x++ ){
Dummy.setName("Alfon");
Dummy.setID("5");
Dummy.setStree("Delta");
Dummy.setName("Neutral");
Person.add(Dummy);
}
return Dummy;
}
Controller 2 for post
#RequestMapping(value="/ajax", method=RequestMethod.POST, consumes = "application/json")
//public #ResponseBody String post( #RequestBody Object ajax_Person_array()) {
public #ResponseBody String post( #RequestBody ArrayList<Person> ajax_Person_array()) {
System.out.println("First TEST");
String Success = "OK";
return Success;
}
Html : get ajax
var ajax_data;
$.ajax({
url: "http://localhost:8080/Person",
async: false,
dataType:'json',
cache: false,
success: function (data) {
ajax_data = data;
alert("success ");
},
error:function(){alert("something went wrong ");}
});
}
Html post ajax
$.ajax({
url: "http://localhost:8080/ajax",
type: 'POST',
dataType: 'text',
data: ajax_data,
// data: JSON.stringify(ajax_data),
contentType: 'application/json',
success: function(data) {
alert(data);
},
error:function(data,status,er) {
alert("error: "+data+" status: "+status+" er:"+er);
document.write(data);
}
});
#RequestMapping (value="/ajax", method=RequestMethod.POST, consumes = "application/json")
public #ResponseBody JSONObject post( #RequestBody JSONObject person) {
//Pass data to a service to process the JSON
}
For your ajax request, do not set dataType to 'Text'. Set it to JSON
$.ajax({ url: "http://localhost:8080/ajax",
type: 'POST',
dataType: 'json',
data: JSON.stringify(ajax_data),
contentType: 'application/json',
success: function(data) {
alert(data);
},
error:function(data,status,er) {
alert("error: "+data+" status: "+status+" er:"+er);
document.write(data);
}
});

Call Web Service method that insert an object from jquery ajax

I have a web service method similiar to this:
#Path("/insert_update")
#POST
#Consumes({ MediaType.APPLICATION_JSON })
#Produces({ MediaType.APPLICATION_JSON })
public Object insert(User obj) {
...(insert and return object)
}
And I want to call this method from jquery, using ajax. I've tried something like this:
var rootURL = "http://Path/to/my/web/service";
function insertUpdate() {
var user = {'name' : $("#name").val(),
'surname' : $("#surname").val(),
'surname1' : $("#surname1").val(),
'usertxt' : $("#usertxt").val(),
'password' : $("#password").val() };
$.ajax({
url : rootURL + "/insert_update",
type : "POST",
contentType: 'json',
dataType : "json",
data : user,
success : function(data) {
alert(JSON.stringify(data));
},
error : function(data) {
}
});
}
Is this code correct? When I try to use it I get this response:
Failed to load resource: Request header field Content-Type is not allowed by Access-Control-Allow-Headers.
XMLHttpRequest cannot load ... . Request header field Content-Type is not allowed by Access-Control-Allow-Headers.
I hope you can help me.
Greetings.
UPDATE
The web service is in the same machine, but in other port. I run the web service project on a WebSphere Application Server and then I only open the HTML file to test my code.
I have other method I don't have problem with, like this:
#Path("/all")
#GET
#Produces(MediaType.APPLICATION_JSON)
public Object all() {
...(get all users)
}
And the JQuery method for this code:
function all() {
$.ajax({
url : rootURL + "/all",
type : "GET",
dataType : "json",
success : function(data) {
$("#tabla tbody:last").empty();
$.each(data.data, function(i, item) {
$("#tabla tbody:last").append("<tr><td>"+item.id+"</td><td>"+item.name+
"</td><td>"+item.surname+"</td><td>"+item.surname1+"</td><td>"
+item.usertxt+"</td><td>"+item.password+"</td></tr>");
});
},
error : function(data) {
}
});
}
This works fine, I have no problem...but I had to donwload an extension for Chrome to test locally, Allow-Control-Allow-Origin.
Why with GET method I have no problem and with POST method yes???
Greetings.

Json Data Not mapped in the backend service

I have a Spring MVC web application and I have the following web service.
#RequestMapping(value = "/newBill", method = RequestMethod.POST)
public #ResponseBody ModelMap acceptNewBill(#ModelAttribute ("Bill") Bill newBill ){
Bill bill = new Bill();
bill.setTableName(newBill.getTableName());
bill.setRoom(newBill.getRoom());
bill.setCovers(newBill.getCovers());
ModelMap model = new ModelMap();
model.put("status", true);
return model;
}
The following Script performs the front end functions.
$('.done').click(function(){
var jsonObject = createJSON(".newBill");
jQuery.ajax({
url: "/newBill",
type: "POST",
data: {bill: JSON.stringify(jsonObject) },
dataType: "json",
beforeSend: function(x) {
if (x && x.overrideMimeType) {
x.overrideMimeType("application/j-son;charset=UTF-8");
}
},
success: function(result) {
alert('sadgsd');
}
});
});
function createJSON(elementToConvert) {
jsonObj = [];
$( elementToConvert + " input").each(function() {
var id = $(this).attr("class");
var email = $(this).val();
item = {}
item [id] = email;
jsonObj.push(item);
});
return jsonObj;
}
The above createJSON function go through a provided html element and puts the values into an object! The click function performs the POST and the Post contains the following data.
bill [{"tableName":"326432"},{"room":"3462346"},{"covers":"3426234"}]
Now when I debug and check the service, the data which goes from the front end doesn't get mapped in the parameter. I checked whether the variable names are the same as the POST. They are the same! but the values doesn't get mapped! Can any one please help me with this issue.
Update :
I changed the service method to GET and passed a value as a URL variable. Then it got mapped in the service param. The problem is in the POST.
Instead of using #ModelAttribute in your controller use #RequestBody:
public #ResponseBody ModelMap acceptNewBill(#RequestBody Bill newBill) {
On the ajax call, set the content type to application/json and stringify the whole object instead of just the array:
jQuery.ajax({
url: "/newBill",
type: "POST",
data: JSON.stringify({bill: jsonObject}),
dataType: "application/json",
beforeSend: function(x) {
if (x && x.overrideMimeType) {
x.overrideMimeType("application/j-son;charset=UTF-8");
}
},
success: function(result) {
alert('sadgsd');
}
});