Cannot retrieve data sent by restfulwebservice in Java - java

I sent Json as post request from Javascript by restfulwebservice but the break point never breaks in Java file which is post type and consumes application/json
HTML:
var url = "http://localhost:8080/RestfulInEMS/user/admin";
empJson = {Username:x[1],IdentityNo:x[2]};
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", url, true);
xmlhttp.setRequestHeader("Content-type", "application/json");
xmlhttp.send(empJson);
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 4){
var result= xmlhttp.responseText;
}
}
JAVA:
#POST
#Consumes(MediaType.APPLICATION_JSON)
public void AddEmployee(JSONObj input)
//here JSONObj is class with data variables same as key name in JSON object sent

I got the Solution :
Problem:
xmlhttp.send(empJson);
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 4){
var result= xmlhttp.responseText;
}
}
Solution:
xmlhttp.send(JSON.stringify(empJson));
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 4){
var result= JSON.parse(xmlhttp.responseText);
}
}
Explanation:
I need to convert it to string to pass as Json and used Jackson libraries for mapping it to class directly and while recieving it i recieve as text and use Json.parse to parse into a object.

Related

How to read the KEY values from JSONObject in angular response from SprinBoot ResponseEntity

In my Spring Boot backend i created a JSON Object from a HashMap
HashMap<String, ClassData> val = obj.unZipIt(file.getOriginalFilename());
Gson Jobj = new Gson();
System.out.println(Jobj.toJson(val));
return ResponseEntity.status(HttpStatus.OK).body(Jobj.toJson(val));
In my Angular Frontend i take the JSON Object response
obj= {};
.subscribe(event => {
if (event.type === HttpEventType.UploadProgress) {
this.progress.percentage = Math.round(100 * event.loaded / event.total);
} else if (event instanceof HttpResponse) {
console.log(event.body);
this.obj['Classes'] = Object.values(event.body);
console.log(this.obj['Classes']);
document.getElementById("demo-content").style.display = "none";
}
}, (err) => {
(err.error instanceof Error)
let message = (`Code ${err.status}, Error was: ${err.error.errorMessage}`);
alert(message)
}
);
when i print my event.body it gives the JSON Response
{"FileProcessor":{"filepath":"C:\tmp\untitled\src\FileProcessor.java","conceptList":[]},"subClass":{"filepath":"C:\tmp\untitled\src\subClass.java","conceptList":[{"parentClassName":"Main","parentPath":"C:\tmp\untitled\src\Main.java","conceptName":"Inheritence","lineNo":1}]},"ProjectProcessor":{"filepath":"C:\tmp\untitled\src\ProjectProcessor.java","conceptList":[]},"Main":{"filepath":"C:\tmp\untitled\src\Main.java","conceptList":[]},"ProjectReader":{"filepath":"C:\tmp\untitled\src\ProjectReader.java","conceptList":[]}}
when i tries to take the key Values out this.obj['Classes'] = Object.values(event.body);
it gives array which is separated from single character
is there a way to get the KEY values From the JSON object

Send JSON by ajax and get parameters by request in JSP

I need to send a JSON object by ajax (with Jquery) and get all parameters by the request Object in JSP (server side).
My JS code is:
var request = new Object();
request.param1= "value1";
request.param2 = "value2";
$.ajax({
type:'GET',
url: 'test.jsp',
//data: {request:JSON.stringify(dataSend)},
//data: {request:dataSend},
//data: JSON.stringify(request),
data:request,
async:true,
success:function(r){
console.log(r);
},
error:function(error){
console.log(error);
}
});
And my JSP code is:
<%#page import="cl.test.pos.web.delegate.POSXXXXXXXX"%>
<%#page import="org.json.simple.JSONObject"%>
<%
JSONObject j = new JSONObject();
if(session.getAttribute("role") != null ){
POSXXXXXXXX bx = new POSXXXXXXXX();
String je;
je = bx.setTest(request);
out.print(je);
out.close();
}else{
j.put("responseStatus","EXCEPTION");
request.getSession().invalidate();
out.print(j);
out.close();
}
%>
And the Method Class is
public String setTest(HttpServletRequest request) throws IOException{
JSONObject j = new JSONObject();
try{
j.putAll(request.getParameterMap());
j.put("responseStatus", "OK");
}catch(FrameworkException e){
/*Any code*/
}catch(Throwable t){
/*Any code*/
}
return j.toJSONString();
}
I Expect return a JSON Object on client and this is so, but, the response is like this:
{"param1":[Ljava.lang.String;#182f12f,"param2":[Ljava.lang.String;#1a881f5}
Values are not understandable and if I send Objects and Arrays, it are so wrong too, for example:
{"parametro4[1][p3]":[Ljava.lang.String;#c5954b,"parametro4[1][p4]":[Ljava.lang.String;#1cc9339,"parametro5[arr1][]":[Ljava.lang.String;#1d5af30}
Please Help me to get All parameters on a JSONObject from HttpServletRequest. I really need to know the best way to do this.
(I already searched in StackOverFlow and the surfing in the web, and I cannot found The best way to do this).
The parameterMap value is an Array Object and not String:
Returns: an immutable java.util.Map containing parameter names as keys
and parameter values as map values. The keys in the parameter map are
of type String. The values in the parameter map are of type String
array.
javadoc for getParameterMao
So you will need to code it, just iterate throught the map and put the parameter name/value in the object.
I already resolved this problem (almost at all), from this way:
public String setTest(HttpServletRequest request) throws IOException{
JSONObject j = new JSONObject();
try{
JsonParser jp = new JsonParser();
Map m = request.getParameterMap();
Gson gi = new Gson();
String stringJson = gi.toJson(m);
j.put("jsonParse",jp.parse(stringJson));
j.put("responseStatus", "OK");
}catch(FrameworkException e){
/*Any code*/
}catch(Throwable t){
/*Any code*/
}
return j.toJSONString();
}
and server response correctly (almost):
{"jsonParse":{"parametro5[arr1][]":["1","2","3"],"pagoAbono":["false"],"parametro4[1][p4]":["3"],"parametro4[1][p3]":["2"],"parametro1":["parametro1"],"parametro4[0][p2]":["1"],"codigoCaja":[""],"parametro5[arr2][1][0][letraX]":["x"],"numeroCheque":[""],"facturasPagos":["195310|234509"],"rutCliente":["154809597"],"banco":[""],"caducidadMes":[""],"parametro4[0][p1]":["0"],"parametro5[arr2][1][]":["x","x"],"numeroTarjeta":[""],"caducidadYear":[""],"montoTotalPago":["334772"],"nombreTitular":[""],"parametro5[arr2][0][]":["a","b","c"],"parametro3[]":["a","b","c"],"parametro2[atributo1]":["atributo1"]},"responseStatus":"OK"}
The only Detail is that the Arrays and Objects are interpreted like the request parameter instead the real Javascript JSONObject.
For example:
If client send this:
var obj = new Object();
obj.param1 = [1,2,3];
Server response this:
obj[param1][0]=1;
obj[param1][1]=2;
obj[param1][2]=3;
Instead to response:
obj.param1[0]=1;
obj.param1[1]=2;
obj.param1[2]=3;
I hope you can understand the problem, and give to me a clue or solution.

Javascript won't post into DIV?

So the console shows that the data is being sent and received but for some reason (probably the conditional) nothing is posted in the specified div tag
var var_IDdatacheck = <?php echo $javaid; ?>;
var var_IDcheck = parseInt(var_IDdatacheck);
//datacheck
var var_numdatacheck = <?php echo $datacheck; ?>;
var var_numcheck = parseInt(var_numdatacheck);
function activitycheck() {
$.ajax({
type: 'POST',
url: 'feedupdate.php',
data: {function: '3test', datacheck: var_numcheck, javaid: var_IDcheck},
success: function (check) {
console.log(check);
var verify = JSON.parse(check);
if (var_IDcheck < verify.id) {
var_IDcheck = verify.id;
for (var i=0;i<var_IDcheck;i++){
$('#datacheck').html(verify[i]);
}
}
setTimeout(activitycheck(),5000);
},
error: function(check) {
console.log(check);
setTimeout(activitycheck(),5000);
}
});
}
$(document).ready(function() {
activitycheck();
}); // document ready
Your id from the JSON is a string, and you are comparing it with an integer
try
var verify = JSON.parse(check);
if (var_IDcheck < parseInt(verify.id)) {
var_IDcheck = parseInt(verify.id);
for (var i=0;i<var_IDcheck;i++){

Jax-RS and Xmlhttp Communication

I have a REST Server in Java JAX-RS and an HTML page.
I want to send a JSON array, a username, and an accountID from the HTML page through an xmlhttp POST request by making all of them a single big String so I can use the xmthttp.send() method.
The HTML sending code is:
function sendData() {
var req = createRequest();
var postUrl = "rest/hello/treeData";
var dsdata = $("#treeview").data("kendoTreeView").dataSource.data();
var accID = "onthespot";
var username = "alex";
req.open("post", postUrl, true);
req.setRequestHeader("Content-type","text/plain");
req.send("data=" + JSON.stringify(dsdata) + "&username=" + username + "&accID=" + accID);
req.onreadystatechange = function() {
if (req.readyState != 4) {
return;
}
if (req.status != 200) {
alert("Error: " + req.status);
return;
}
alert("Sent Data Status: " + req.responseText);
}
}
And the Server JAX-RS code is:
#Path("/treeData")
#POST
#Consumes(MediaType.TEXT_PLAIN)
#Produces(MediaType.TEXT_PLAIN)
public String storeTreeData(
#QueryParam("data") String data,
#QueryParam("username") String username,
#QueryParam("accID") String accID) {
System.out.println("Data= " + data + "\nAccID= " + accID + "\nUsername= " + username);
return "Done";
}
The problem is that all the variables are printed as null..
the storeTreeData function should find the data , username , accID variables through #QueryParam and store them isn't that right?
Anyone know what's the problem here?
PS:The xmlhttp request is initiallized correctly and the connection is made but the parameters are not passed on the server.
What you try to do:
#QueryParam is used to get parameters from the query of the request:
http://example.com/some/path?id=foo&name=bar
In this example id and name can be accessed as #QueryParam.
But you are sending the parameters in the body of your request.
What you should do:
To get the parameters from the body, you should use #FormParam together with application/x-www-form-urlencoded:
#Path("/treeData")
#POST
#Consumes(MediaType.APPLICATION_FORM_URLENCODED)
#Produces(MediaType.TEXT_PLAIN)
public Response storeTreeData(
#FormParam("data") String data,
#FormParam("username") String username,
#FormParam("accID") String accID) {
// Build a text/plain response from the #FormParams.
StringBuilder sb = new StringBuilder();
sb.append("data=").append(data)
.append("; username=").append(username)
.append("; accId=").append(accID);
// Return 200 OK with text/plain response body.
return Response.ok(sb.toString()).build();
}
Edit:
You should also use
req.setRequestHeader("Content-type","application/x-www-form-urlencoded");
in your JavaScript code.

how to return multiple json objects from java servlet using one ajax request

I am building web application using jsp and servlet, I send ajax request from jsp and I want to return two json objects from servlet. I tried to do the following but the code did not work.
// in jquery I wrote this code
var id = $(this).attr('id');
var paramenters = {"param":id};
$.getJSON("MyServlet", paramenters, function (data1,data2){
$("h3#name").text(data1["name"]);
$("span#level").text(data1["level"]);
$("span#college").text(data2["college"]);
$("span#department").text(data2["department"]);
});
// in the servlet I wrote this code
String json1 = new Gson().toJson(object1);
String json2 = new Gson().toJson(object2);
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
response.getWriter().write(json1);
response.getWriter().write(json2);
can someone help me???
You should do it like this:
Server side:
String json1 = new Gson().toJson(object1);
String json2 = new Gson().toJson(object2);
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
String bothJson = "["+json1+","+json2+"]"; //Put both objects in an array of 2 elements
response.getWriter().write(bothJson);
Client side:
$.getJSON("MyServlet", paramenters, function (data){
var data1=data[0], data2=data[1]; //We get both data1 and data2 from the array
$("h3#name").text(data1["name"]);
$("span#level").text(data1["level"]);
$("span#college").text(data2["college"]);
$("span#department").text(data2["department"]);
});
Hope this helps. Cheers
Wrap them in JSON array:
[ {..}, {..}, {..}]
or, wrap them in another object:
{ "result1":{..}, "result2":{..} }
You could return a JSON array with both objects as elements of the array. Have your servlet return JSON that has a structure like this one:
[{"name": "object1"}, {"name": "object2"}]
Then your javascript code can be something like this:
$.getJSON("MyServlet", paramenters, function (data){
var data1 = data[0];
var data2 = data[1];
$("h3#name").text(data1["name"]);
$("span#level").text(data1["level"]);
$("span#college").text(data2["college"]);
$("span#department").text(data2["department"]);
});
you're going to need to put both into a single json string like so
response.getWriter().write("[");
response.getWriter().write(json1);
response.getWriter().write(",");
response.getWriter().write(json2);
response.getWriter().write("]");
this puts them in a json array
you could also put them in a json object
response.getWriter().write("{\"object1\":");
response.getWriter().write(json1);
response.getWriter().write(",\"object2\":");
response.getWriter().write(json2);
response.getWriter().write("}");
#Edgar 's answer works for me. But I think we should avoid to form the array by ourselves, so I suggest to use a list. The codes will be something like this:
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
...
resp.setContentType("application/json");
resp.setCharacterEncoding("utf-8");
ArrayList<Object> obj_arr = new ArrayList<Object>();
obj_arr.add(obj1);
obj_arr.add(obj2);
Gson gson = new Gson();
String tmp = gson.toJson(obj_arr);
resp.getWriter().write(tmp);
}
And in the front end, for the data we get, we can use data[0] to retrive obj1 and data[1] to retrive obj2. The codes will be something like this (I am using ajax here):
$('#facts_form').submit(function (e) {
e.preventDefault();
var data = new FormData(this);
var url = 'import';
$.ajax({
url: url,
type: "POST",
data: data,
processData: false,
contentType: false,
async: false,
cache: false,
success: function (data) {
for (var i = 1; i < data.length; i++){
//do whatever
}
},
error: function (xhr, status, error) {
alert(status + "\n" + error);
}
});
});

Categories