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!
Related
Sorry for asking repeated question but I have tried many solutions but none works,
So I have this class and table Draft, in the index.html I have a table containing many data, I want to use ajax to pass all of that data to Controller class in back-end to save that data in the draft table in the database which equivalent to class Draft.
But this error happened Request method 'POST' not supported.
The problem is GET does not return this error and I want to use POST to pass data.
This is my Draft controller class
#Controller
#Secured({"ADMIN","SUPER_ADMIN"})
public class DraftController {
#Autowired
private DraftService draftService;
#PostMapping("/newdraft")
public #ResponseBody Draft AddDraft(#RequestBody Draft draft, BindingResult result) {
draftService.save(draft); // save the draft to database
return draft;
}
}
This is my ajax function
$("#draftFormSubmit").on('click',function(e) {
e.preventDefault();
call_draft();
});
function call_draft() {
var draft = {
"id": 1,
"user_id":5,
"lowest_cost_found":3,
"paper_used":3,
"print_type":3,
"actual_ups_per_paper":3,
"quantity":3,
"color":3,
"size":3,
"gloss_lam":3,
"matt_lam":3,
"water_based":3,
"uv":3,
"varnish":3,
"spot_uv":3,
"emboss_deboss":3,
"hot_stamping":3,
"diecut":3,
"creasing_line":3,
"total_price":3,
"markup":3,
"final_price":3
}
$.ajax({
type: "POST",
contentType: "application/json",
url: "/newdraft",
data: JSON.stringify(draft),
dataType: 'json',
success: function(data) {
alert("success");
console.log(data)
},
error: function() {
alert("failed");
}
});
}
Only in this project the error occurs, when I write a simple POST on another project it does not have this error.
Thank you in advance!
Try to add the following
#Controller
#RequestMapping("/") // <------------
#Secured({"ADMIN","SUPER_ADMIN"})
public class DraftController {
and check again
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");
}
});
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.
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());
}
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 :) ?