How to send an array from Servlet to Java Script with AJAX? - java

I need send an array to js with ajax, this is my function with ajax in a java script...
$.ajax({
url: "/localizacion/ServletPeticiones",
type:"Post",
data:"accion=LatLong_UR",
dataType: "text",
success: function(results){
console.info(results);
cad=results;
}
});
I've got an array String[][] datos, and I have to send this array from my Servlet to JS with the last function.
How I can do this?
How receive the array from my Servlet with my function of ajax in a js?

The servlet will return a application/json response, and a JSON-encoded array (better, you can use a Map<String, String>). There are libraries, like Gson, to do the conversion:
public void doPost(HttpServletRequest request, HttpServletResponse response) {
response.setContentType("application/json; charset=UTF-8");
Gson gson = new Gson();
Map<String, String> datos = getDatos(); // you have to implement this
response.getWriter().println(gson.toJson(datos));
}

You can try using JSON .. you can use google's GSON library to convert an array into JSON representation and send it to your client
On the client side ... change the $.ajax's dataType to "json"
In the success function you just use the returned data as javascript array

JSON would be the right way to go about it. PHP has json_encode function that very well does it for you from arrays. Another way is to manually create a JSON string although it's not a good idea. On the other hand, just for practice and get familiar with JSON, it's advisable, but you are better of using built-in json generating capabilities of your server side platform.
You might want to send a correct header from the server so browsers are able to receive it as json data: "Content-Type: application/json"

Related

Http POST in order to Upload a file and send a JsonString --- send in ReactJs and Receive in Java

I have a to send (upload) a file and send a JsonString in my ReactJs FrontEnd.
The BackEnd is a Java Tomcat.
Code in ReactJs:
const formData = new FormData();
formData.append('file', selectedFile);
formData.append( 'jsonstring', MY_JSONSTRING );
req = new Request(PARAMETRI_URL, {
method: 'post',
headers: new Headers({ "Content-Type": "multipart/form-data"}),
body: formData
});
Code in Java:
#MultipartConfig
protected void processRequest(HttpServletRequest request, HttpServletResponse response) {
..........
final Part PART_Json = request.getPart("jsonstring");
final Part PART_file = request.getPart("file");
It doesn't work!!!
I tried this solution using getPart(), but I don't know if it is the right one.
My target is: the ReactJs FrontEnd send a file and a JsonString to Java BackEnd
I found many posts here, but not with this specific case. I did many tentatives, with differents headers, content-type, ecc...
Can somebody add the piece of codes in both ReactJs and Java side?
in ReactJs: how to build 'req',
in Java: how to process 'request' in
order to extract the jsonstring and the file
I solved using the following post:
How to send a file from JavaScript to a Java WebService
At the end of the story, if you need multipart, in javascript/ReactJs you need to use 'XMLHttpRequest()', no way by 'new Request(...)' followed by 'fetch...'.

Jetty servlet: How can I forward GET request with parameters as POST request with JSON body?

My web clients send GET requests with URL query parameters. The receiving App can only accept POST requests with JSON body. I would like to embed a jetty servlet to the receiving App which converts GET requests to POST request, with url parameters being converted to json format body.
Input GET url for example: http://localhost:8081/?key_1=value_1&key_2=3value_2...&key_n=value_n
Expected POST json payload: {"key_1":"value_1", "key_2":"value_2", ..."key_n":"value_n"}
Could you please illustrate how to implement such functions?
I`ve worked with other programming languages, but am completely new to java. I really really appreciate your help.
Thanks and best regards,
Fischlein
You can read all the query string parameter and put it into HashMap. Then serialize this hashmap using jackson-json api or google gson api.
Jackson Reference Url :
http://wiki.fasterxml.com/JacksonHome
Read the parameters from the get request, create a json string and post it with a utility library like http://hc.apache.org/httpclient-3.x/

How to get JSON data from POST request using Servlet

This is my code on the client side:
$.ajax({
type:'POST',
charset:'utf-8',
url:'http://localhost:8180/GisProject/MainService',
data:JSON.stringify(params),
success:function(msg)
{
console.log(msg);
},
error:function(xhr,status)
{
console.log(status);
},
contentType:"application/json"
});
I have previously parsed this data in Node using express.bodyParser but now I have to parse it using the servlet.I have seen people assign variables here without using JSON.stringify and getting that variable using request.getParameter(myData).
What is the standard way of getting the JSON data into the servlet?
And why do people seem to be sending Javascript objects with JSON embedded as a String within like data:{mydata:JSON.stringify(actualData)}?
In case I was not being clear,I want to use the doPost method's request object to get the data I sent from the client side.
On the server side in a servlet you can read POST data payload from request.getReader()
And you can use JSON library like GSON to parse JSON. Something like:
YourClass obj = new Gson().fromJson(request.getReader(), YourClass.class)
Try this:
$.ajax({
type:"POST",
url:'http://localhost:8180/GisProject/MainService',
data:{mydata:JSON.stringify(params)},
datatype:"json",
success:function(msg)
{
console.log(msg);
},
error:function(xhr,status)
{
console.log(status);
},
});
you can send request and response object to doGet method and than get the json in the same way.
Way to send object to doGet
doGet(request, response); call it in to the post method.
Hope this should help for you:
var obj = jQuery.parseJSON( '{ "name": "John" }' );
alert( obj.name === "John" );

display results in jsp by calling a servlet using jquery ajax?

I want to call a servlet. servlet will fetch the data from database and keeps it in request. And the result i need t display in some.jsp using jstl tags.
$('#ownForm #myButton').click(function() {
$.ajax({
type: "GET",
url: "./controller",
success: function(msg) {
//Todo
},
error: function(ob,errStr) {
//Todo
}
});
});
In servlet i have below code:
//keep database returned list in request
request.setAttribute("myresult", result);
request.getRequestDispatcher("/WEB-INF/some.jsp").forward(request, response);
Please help me how can i achieve it?
Ignore the jsp. Use FlexJson to serialize your result directly from the result object to json. Print the serialized result to the out stream in the response.
Something like this:
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
JSONSerializer serializer = new JSONSerializer();
serializer.exclude("*.class"); //reduce clutter in your output as you see fit
serializer.serialize(objectToSerialize, response.getWriter());
Using jquery, parse this json and act on the result.

PlayFramework. JSONP view. How?

I need that controller return JSONP response.
Something like this:
jsonp123({"name" : "Remy", "id" : "10", "blog" : "http://site.com"});
I know, that PlayFramework can send response as html Template, JSON, XML... but how send JSONP response?
Thanks.
You can take a look at how it's done for JSON (renderJSON() throws a RenderJson object) and implement JSONP response in a similar way. The only difference is that you need to surround Gson output with a function call and that content type should be text/javascript.
You can set the header type to "text/javascript" and then call renderText. (The render methods only set the mime type if you don't.)

Categories