JSONWithPadding Jersey 1.x + jquery - java

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 :) ?

Related

Error javax.json.stream.JsonParsingException: when making an AJAX API call

I have developed a web based program using java jersey in my back end and jsp in my front end. When I make a post API call using Ajax my back end gets the following exception.
javax.json.stream.JsonParsingException: Unexpected char 117 at (line
no=1, column no=1, offset=0)
I guess it's something wrong with the data which I'm passing through the Ajax API call.
Here is my ajax API call:
var obj = JSON.parse('{ "userName":"John", "password":"hgvv", "img":"New York","fname":"kjbjk","lname":"bkbkkj","tp":"buhb","address":"jhbjhb","type":"user"}');
$.ajax({
type: "POST",
url: $url,
contentType: "application/json",
data: obj,
dataType: 'json',
success: function () {
alert("successed");
}
});
This is my back end implemented code:
#Path("testing")
public class test {
UserRepository userRepo=new UserRepository();
#Path("users")
#POST
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public UserModel CreateUser(UserModel a) {
userRepo.createUser(a);
return a;
}
}
You should send the data as a JSON String, not a JSON Object. Avoid the JSON.parse from your code.
var data = '{ "userName":"John", "password":"hgvv", "img":"New York","fname":"kjbjk","lname":"bkbkkj","tp":"buhb","address":"jhbjhb","type":"user"}';
Alternatively, I would construct the JS Object, and apply JSON.stringify on it. This way, the code is more readable:
var data = {
userName: "John",
password: "hgvv",
img: "New York",
fname: "kjbjk",
lname: "bkbkkj",
tp: "buhb",
address: "jhbjhb",
type: "user"
};
$.ajax({
type: "POST",
url: $url,
contentType: "application/json",
data: JSON.stringify(data), // added JSON.stringify here
dataType: 'json',
success: function () {
alert("successed");
}
});

Spring Ajax JQuery Jackson

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.

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

Java Rest call with jquery and ajax

I am making a ajax Rest call within jquery and it is supposed to return me a list of beans, which I want to show in the jsp. I am able to make the Rest call but I can't get how to get the result in the ajax call and show it in page.
jsp page with the ajax call
<script type="text/javascript">
$(document).ready(function(){
$('#abcForm').submit(function(){
var v = $('#abc').val();
$.ajax({
type: "GET",
dataType: "jsonp",
url: "http://localhost:8080/RestTest/rest/hello/"+v,
});
});
});
</script>
java code
#Path("hello")
public class RestController {
#GET
#Path("{param}")
public Response getMsg(#PathParam("param") String msg) {
String output = "Hello : " + msg;
return Response.status(200).entity(output).build();
}
}
So actually there will be a rest call from the java class and it will return a list which needs to be shown in the jsp page as ajax call. This is where I am stuck.
Help needed.
Thanks
You have a success callback that will be called when the request finishes as successful and will receive the response as the first parameter:
$.ajax({
type: "GET",
dataType: "jsonp",
url: "http://localhost:8080/RestTest/rest/hello/"+v,
success: function(data) {
//do something with data.
}
});

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!

Categories