Spring Ajax JQuery Jackson - java

Whats wrong in my approach.
Java Mapping :
#POST
#Path("/receive")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public void consumeJSONList(#RequestBody List<Question> clientList) {
String output = "consumeJSONList Client : " + clientList.toString() + "\n\n";
System.out.println(output);
}`
Ajax Call :
function addData(x) {
var x='[{"id":12,"email": "2","lang": "es"}]';
$.ajax({
type: 'POST',
url: "rest/question/receive",
header : {
"Content-Type":"application/json"
},
data: x,
success: function(data, textStatus, jqXHR){
alert('Wine created successfully');
},
error: function(jqXHR, textStatus, errorThrown){
console.log(jqXHR);
alert(jqXHR+'addWine error: ' + textStatus+"errorThrown"+errorThrown);
}
});
}
i am able hit the same url with same data in google post man but when use ajax call its throwing 415(Unsupported media type)
Please help to create a controller which can accept list of java object and process the same

As the jQuery docs say, you should give the following a try:
Replace…
header : {
"Content-Type":"application/json"
},
…with…
dataType: 'json',
…and make sure that the server's context path in front of "/receive" is really "rest/question". Depending on the situation also a leading slash "/rest/question/receive" could be worth a try.

Related

Return value from JAVA API Value

On the click of a button I am sending a JSON to the Java Server side via an API POST call.On validating the JSON, the server side function return a String.
How do I access that string on my JavaScript client side?
That String will tell me whether the JSON is valid or not.
You can use parseJSON(json) function in jQuery, for example:
function getValue(actionName) {
$j.ajax({
url: actionName + ".do",
data: {
"action" : "getJsonValue"
},
dataType: "json",
success: function(response) {
if (response.errorCode) {
showErrorMessage(response.errorMessage);
return;
}
response = $j.parseJSON(response);
return response;
},
});
}

Failed to load resource: the server responded with a status of 415 (Unsupported Media Type) in Java RESTful web service call

I have the following javascript in my test html page to send ajax requests to a java restful web service I built with netbeans (mostly auto generated by using 'Restful web services from database' function).
Here is the ajax query from my test html page:
$(function(){
$('.message-button').on('click', function(e){
var resultDiv = $("#resultDivContainer");
$.ajax({
headers: { 'Accept': 'application/json',
'Content-Type': 'application/json'
},
'type': 'POST',
'url': 'http://localhost:8080/xxxAPI/api/activity',
'data': { "baseItemId": "2" },
'dataType':'json',
'success': function(data) {
var xmlstr = data.xml ? data.xml : (new XMLSerializer()).serializeToString(data);
$("#resultDivContainer").text(xmlstr);
},
'error': function(jqXHR, textStatus, errorThrown) {
alert(' Error in processing! '+textStatus + 'error: ' + errorThrown);
}
});
})
});
Also here is the part of my java code that accepts post requests:
#POST
#Override
#Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public void create(XxxxxActivity entity) {
super.create(entity);
}
When I request from the test page (for this version of the test page), I get this error:
Failed to load resource: the server responded with a status of 415
(Unsupported Media Type)
or this error:
POST http://localhost:8080/xxxAPI/api/activity 415 (Unsupported
Media Type)
So far I have tried making various changes to the ajax request as advised on similar questions on stackoverflow, including changing type to jsonp, putting json data in double quotes, adding headers and changing data type to xml. None of them have worked.
Also since I manage to get a response from the server at times, I wonder if the issue is with xml parsing in the java code. I believe a potential fix would be to add the jackson jar files, but I have no idea how to add them on netbeans as there is no lib folder in WEB_INF.
I would also like to know if there is any issue with the jquery ajax request. This issue has been bugging me for days.
PS: Also note that GET requests from the browser work fine. I have not used maven in this project.
Replace
'data': { "baseItemId": "2" },
with
'data': JSON.stringify({ "baseItemId": "2" }),
Object JSON is available here.
EDIT
add attribute contentType: 'application/json; charset=UTF-8'
remove attribute headers from ajax call.
Frondend
$.ajax({
contentType: "application/json; charset=utf-8",
url: '/GetList',
type: 'POST',
dataType: 'json',
data: JSON.stringify({ 'Name': 'mehmet erdoğdu'}),
beforeSend: function () {
}, success: function (data) {
}, complete: function () {
}, error: function (data) {
}
});
Backend
[HttpPost]
public JsonResult GetList([FromBody] NameRequest req)
{
var selectListItems = new List<SelectListItem>
{
new SelectListItem
{
Value = "",
Text = "Select Name"
}
};
//
return Json(selectListItems, new JsonSerializerSettings());
}

angularjs add headers in ngResource

I am building a web-based application by using Java servlet and AngularJs.
Previously, I just use $http (the following code), every things is fine.
this.callWithParam = function(command) {
var deferred = $q.defer();
$http({
method: 'POST',
url: 'SearchServlet',
data: $.param({'data': JSON.stringify(command)}),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function(data) {
deferred.resolve(data);
}).error(function() {
deferred.reject('Error occur!');
});
return deferred.promise;
}
But I want to revise it into $resource, because I find that it is really convenience and can save a lot of code. So I write the following code
search: function() {
return $resource('SearchServlet', {}, {
'searchA': {method: 'GET', headers:{'Content-Type': 'application/x-www-form-urlencoded'} },
'searchB': {method: 'GET', headers:{'Content-Type': 'application/x-www-form-urlencoded'} }
});
}
But I found that the header failed to add to the request headers, then it has the problem to due with Chinese character, so the servlet cannot well receive the Chinese words.
Therefore, anyone has the idea to solve this problem? Thanks!

JSONWithPadding Jersey 1.x + jquery

Hello I 'm trying to make a rest call from jquery into a jersey 1.18 server using jsonp
#GET
#Path("jsonp")
#Produces("application/x-javascript")
public JSONWithPadding testJSONP(#QueryParam("callback") String callback){
String retVal="YES";
return new JSONWithPadding( new GenericEntity<String>("{\"test\":\"" + retVal + "\"}"){},callback);
}
and the jquery:
$.ajax({
url: 'http://localhost:9280/manager/jsonp',
type: 'GET',
dataType: 'jsonp',
jsonp: 'callback',
success: function(data){
console.log("success");
alert(data.test);
}
});
ALthough, it seams that JSONWithPadding is not functioning properly, firefix's console returns:
SyntaxError: missing ; before statement jsonp:1
the content of the jsonp is:
{
"callbackName":"jQuery111109478052598614781_1410424986004",
"jsonSource":{
"rawType":"java.lang.String",
"type":"java.lang.String",
"entity":"{\"test\":\"YES\"}"}
}
Any help :) ?

AJAX Post - Performed in JSP, need to return java based variables in the AJAX POST Success function

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);
},

Categories