1

I'm sending data via post request from the webpage to the server.

$("#1, #2, #3, #4").on("click", function(){
            console.log($(this).attr("id"));
              var xhr = new XMLHttpRequest();
              xhr.open("POST", "SimpleServlet.html", true);
              xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
              xhr.send(JSON.stringify({"product_id": $(this).attr("id"), "quantity" : 1 }));
            });

With the help of this javascript. I am sure that it gets sent to the server and it arrives there.

On the server I try to retrieve the values I wrote to the data.

.post("SimpleServlet.html", ctx ->
                    {
                        final Response response = ctx.getResponse();

                        System.out.println("Getting result");

                        final ExecResult<String> result = ExecHarness.yieldSingle(c ->
                                ctx.parse(String.class));


                        System.out.println("Getting value");
                        response.send("webshop.html");
                    })

I, unfortunately, didn't find any guide how to retrieve the String values accordingly.

I tried the above but this does get stuck inside the ExecHarness forever.

I would like get receive the values. Take them to make a new java object and then respond with the json of another java object back. (Second object depends on previous object data)

raycons
  • 735
  • 12
  • 26

1 Answers1

2

Ratpack's API reference Instead of ExecHarness try something like this:

ctx.getRequest().getBody().then({ data ->
  String text = data.getText();
  // parse text with whatever you use, e.g. Jackson

  System.out.println("Getting value");
  response.send("webshop.html"); 
})

You can chain it too, e.g.

context.getRequest().getBody().flatMap({ data ->
    //parse data and get id
    //call to async service who returns Promise
    return service.getReport(id).map((String report) -> {
        // do some staff
    })
 }).then({
     //final staff before send response
     //import static ratpack.jackson.Jackson.json; 
     context.getResponse().send(json(result).toString());
 })
SDen
  • 191
  • 3
  • 5
  • Seems complicated for just getting request body. At least I know a way now. Thanks. – Manish May 11 '18 at 09:23
  • Well, it is typical in async world .. just some other frameworks\libraries (e.g Spring Web Flux) can provide some kind of extra wrapper to make it nicer ... but in the end of the day you are dealing with the same async pattern ... it will just be a habit for you ... especially if you have an experience with Promises in JavaScript world :) – SDen May 14 '18 at 09:53