I am trying to send a List of JSON objects into a post request. I keep getting a 500 error here. I feel like i am not setting up my variable in the Method definiton to the right data type but im not sure what it should be set too.
AJAX Request:
function post_request(json_data) {
$j.ajax({
url : '../api/createDisplayGroup/postHtmlVar/' + containerID[1] + '/' + containerType[1],
data: JSON.stringify(json_data),
dataType: 'json',
type : 'post',
contentType : 'application/json'
}).done(function(response) {
run_update(response);
}).error(function(jQXHR, textStatus, errorThrown) {
alert('error getting request');
});
};
Java REST Service (POST only):
#POST
#Path("/postHtmlVar/{containerId}/{contentType}")
#Consumes(MediaType.APPLICATION_JSON)
public List<TabDefinition> postHtml(#PathParam("containerId") String containerId, #PathParam("contentType") String contentType, List<JSONObject> displayGroups) {
Long contId = Long.parseLong(containerId);
Long contType = Long.parseLong(contentType);
//return convertToResponse(peopleFilterService.getDisplayGroups(contId, contType));*/
return testDisplayGroup();
}
You need to take the input json string as a #FormDataParam. I don't think your JAVA REST framework can marshal the json to a list of JSONObject. You may have to create a class representing the json data and define your method like this:
public List<TabDefinition> postHtml(#PathParam("containerId") String containerId, #PathParam("contentType") String contentType, #FormDataParam MyJSonDataClass myJsonDataClassObj) {
Related
I am trying to post a json using ajax to my spring mvc controller I am using code like this in my js file:
$('#regist').click(function () {
$.ajax({
url: 'user/regist',
contentType: "application/json; charset=utf-8",
type: 'post',
dataType: 'json',
success: function (data) {
var json = JSON.stringify(data);
alert(json);
},
fail: function (errMsg) {
alert(errMsg);
},
data: JSON.stringify({
'IDCard': '1234567890'
})
})
});
the signature of my controller function is like this:
#RequestMapping(value = "/regist", method = RequestMethod.POST)
#ResponseBody
public ResultJson regist(HttpSession session, #RequestBody RegistFormJson json)
the RegistFormJson goes like this:
public class RegistFormJson {
private String IDCard;
public String getIDCard() {
return IDCard;
}
public void setiDCard(String IDCard) {
this.IDCard = IDCard;
}
}
now when I send my request, and what I get from my controller using
logger.info(json.getIDCard);
is null.When I change my bean propertity to idCard and change my other code as well ,I can get the result successfully. Who can tell me why ? And If I want to use IDCard in my code, how can I get the result .Thanks
Spring comes with Jackson API which uses Standard Java Code Convention to map JSON properties to Java models.
Since IDCard is not in lower camel case, Jackson API is not able to map the JSON property.
To overcome this you need to specify a #JsonProperty("IDCard") annotation on a Java attribute in order to use IDCard for your JSON property.
Likewise, you can set the PropertyNamingStrategy on the ObjectMapper to overcome this issue.
What I am trying to do is initiate an ajax call from my frontend code by user interaction. This calls a Java Restful service that I have written. And this Java function calls another service.
I need that java service in the middle because I need to send the inputs to other service in the format of "MyModel".
The problem is, the AJAX call works but it cannot get the JSON object that I send. You see in the Java function below I create the "param1" : "asdasd" for the second time there. That's because it cannot get the JSON data from front-end. It should be dynamically created with the argument of sendInputs function.
By the way when I debug the value String input is like this: ""
Javascript AJAX call:
var paramData = {"param1" : "asdasd"};
$.ajax({
type : 'GET',
url : "/api/v2/proxy",
dataType : "json",
headers : {
"Service-End-Point" : "http://localhost:9000/service/myService/sendInputs"
},
statusCode : {
200 : function(data) {
}
},
contentType : "application/json",
data : JSON.stringify(paramData),
error : function(error) {
}
});
Java consume:
#GET
#Path("/sendInputs")
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public String sendInputs(String input) {
String result = null;
//define the service endpoint to be added the default URL
String serviceEndpoint = "otherService/tool/runTool";
List<MyModel> modelParameterList = new ArrayList<MyModel>();
MyModel inputParameter = null;
inputParameter = new MyModel("param1", "asdasd");
modelParameterList.add(inputParameter);
//convert the Java Map to a json string using Jackson ObjectMapper
String jsonStringOfInputParameters = toJSON(modelParameterList);
WebClient client = WebClient
.create("http://localhost:9000");
result = client.path(serviceEndpoint)
.query("tool", "myTool")
.query("input", jsonStringOfInputParameters)
.accept("application/json")
//tells cxf to convert the json to a string type upon return
.get(String.class);
// Return the json result as a string
return result;
}
your paramData variable is already a valid json. I do not think you need yo use JSON.Stringify() again.And what is this is the ajax call:
statusCode : {
200 : function(data) {
}
}
Status code is supposed to be coming from the server in response.
First, your ajax header should be like this:
headers: {
Accept: "application/json; charset=utf-8",
"Content-Type": "application/json; charset=utf-8"
},
url:
url: "http://localhost:9000/service/myService/sendInputs"
Second, you need to have MyModel with param1 field and Also setters and getters. And this can be your service method:
public String sendInputs(MyModel model)
{
//model.getParam1() will be "asdasd"
}
I am sending these data to Restful Web Service (Jersey) using jQuery code and the method POST:
var dataString = {"id":1,"status":"passed","session":"nothing"};
$.post("https://localhost:8443/pv01/ws/user/cookie", dataString);
And with this data, I am sending a cookie. The data in te cookie come from an external API.
The problem what I am facing is how to receive the cookie value and the dataString together.
Here's my Java code to read a Cookie :
#POST
#Path("cookie")
public String cookie(#CookieParam("L14c") String str) {
Logger.getLogger(Main.class.getName()).log(Level.INFO, "message : " + str );
return str;
}
And for the data, I can do like this :
#POST
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
#Path("cookie")
public String cookie(DataString dataString) {
Logger.getLogger(Main.class.getName()).log(Level.INFO, "message : " + dataString );
return "ok";
}
But when I combine the two methods to accept cookie and the JSON dataString, I got Error 415, Unsupported media type!
I tried to look on HTTP Headers, but I can access only cookies.
The problem is with the jQuery request. It looks like the Content-Type is defaulting to application/x-www-form-urlencoded. You should use a Browser debugger like Firebug. Makes it easier to spot these kind of things.
From what I've tested, it should work with something like
$.ajax({
url: theUrl,
type: "POST",
data: JSON.stringify(dataString),
dataType: "json",
contentType: "application/json",
success: function(response) {
alert(JSON.stringify(response));
}
});
I am trying to send JSON array of string and perform some task on serverside.
Here is my JS:
var x = ["Salam","Saghol","11"]
$.ajax({
url: '../rest/group/addusers',
type: 'POST',
data: JSON.stringify(x),
contentType: 'application/json',
dataType: 'json',
async: false,
success: function(msg) {
alert(msg);
}
});
And my Java method:
#POST
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
#Path("/addusers")
public Response addUsersToGroup(List<String> users) {
System.out.println(users);
return Response.status(Response.Status.OK).entity("Salam").build();
}
When I send the request I get "415 (Unsupported Media Type)" error message.
Please help me just passing the array elements (Strings) to the method below.
Thanks in advance.
P.S. Here are my headers:
The problem here is that the "users" parameter can't be deserialized. While my idea might be clear, the logic is not correct enough programmatically.
Usually data from POST are extracted using query parameters (using "=","?","&" as separator). In my case I put the data directly to POST output stream. And getting all data in string representation is more logical.
So I changed the code into this:
#POST
#Produces(MediaType.TEXT_HTML)
#Consumes(MediaType.APPLICATION_JSON)
#Path("/addusers")
public Response addUsersToGroup(String users) throws IOException {
ObjectMapper mapper = new ObjectMapper();
List<String> l = mapper.readValue(users, List.class);
for (String s : l) {
System.out.println("Item: "+s);
}
return Response.status(Response.Status.OK).entity("Salam").build();
}
And problem is solved. Thanks for attention.
I am using ajax post within a JSP, to send json data to a servlet java class. Within the servlet controller class I used getparameter to get the data being sent from the calling JSP.
This all works fine, to this point. I then initate processing of the data in from this servlet class, and I need to formulate a data response to send back to the calling JSP.
Is there a way that I can hold the data in variables within the servelt class, and as part of the success function (within my AJAX post) access this data?
My AJAX Post code:
$.ajax({
type: "POST",
url: url,
dataType: "text", // [text, xml, json, script, text, html]
data: {postData : myData, sendURL : postUrl},
success: function(data, textStatus, jqXHR) {
alert('Success post to URL entered \n\n The data returned the following: ' + data);
},
error:function (xhr, ajaxOptions, thrownError){
alert('Error xhr : ' + xhr.status);
alert('Error thrown error: ' + thrownError);
}
//complete: alert('complete')
});
My Servlet Controller code:
#RequestMapping("/postData")
public String postData(Model model, HttpServletRequest request) throws Throwable{
String postData = request.getParameter("postData");
String sendURL= request.getParameter("sendURL");
System.out.println(this.getClass() + " : postData : " + postData);
System.out.println(this.getClass() + " : gatewayURL : " + gatewayURL);
/* Process data and formulate a response.... */
String responseText = processedResponseText; // This processedResponseText was populated in the internal processing
String responseCode = processedResponseCode; // This processedResponseCode was populated in the internal processing
return "callingJSP";
}
As part of my AJAX Post - Success function, how can I get these two variables (responseText and responseCode) back to the calling JSP?
Many thanks
If you know the structure of the data that's coming in (you should!), create an object that the post data can be serialized to (I'm assuming myData is json?... if not, it should be!) by the servlet. The spring framework provides the #RequestBody annotation to deserialize the incoming json to your object. When the servlet needs to respond, do what #Jigar recommended: wrap your response in an object. The spring framework provides the #ResponseBody annotation to serialize your response to json. It could look something like this:
Your js:
var myData = { postId: 1, comment: "this is great!" };
$.ajax({
type: "POST",
url: url,
dataType: "text", // [text, xml, json, script, text, html]
data: {postData : myData, sendURL : postUrl},
success: function(data, textStatus, jqXHR) {
var jsonRepsonse = JSON.parse(data);
alert('Success post to URL entered \n\n The data returned the following: ' + jsonRepsonse.responseText + ", " + jsonRepsonse.responseCode);
},
error:function (xhr, ajaxOptions, thrownError){
alert('Error xhr : ' + xhr.status);
alert('Error thrown error: ' + thrownError);
}
//complete: alert('complete')
});
Your Java object:
class Comment {
private long postId;
private String comment;
// getters & setters
}
Your wrapped response object:
class AjaxResponse{
private String responseText;
private String responseCode;
//other stuff
}
The handler function in your controller:
#RequestMapping("/postData")
public #ResponseBody postData(Model model,
#RequestBody Comment comment,
HttpServletRequest request) throws Throwable{
String sendURL= request.getParameter("sendURL");
System.out.println(this.getClass() + " : comment : " + comment.toString());
/* Process data and formulate a response.... */
AjaxResponse ajaxResponse = new AjaxResponse(processedResponseText, processedResponseCode);
return ajaxResponse;
}
Ideally your AjaxResponse contains another object instead of text that provides more information about the response. For example, you may want to change your AjaxResponse object as follows:
class CommentResponse extends Comment {
private long commentId;
private Timestamp entryDateTime;
// etc
}
class AjaxResponse{
private CommentResponse commentResponse;
private String responseCode;
//other stuff
}
Doing this helps you immensely when receiving the response on the front end, but it depends on what you need.
Also..
Success will return the response
success: function(data, textStatus, jqXHR) {
alert('Success post to URL entered \n\n The data returned the following: ' + data);
},
No need of XHR and textStatus in the success function should be like :
success: function(response) {
alert('Success post to URL entered \n\n The data returned the following: ' + response.responseText);
},