How to pass JSON String to Jersey web rest service with mail request

I want to create a REST Jersey web service that takes a JSON string as an input parameter.

I will also use post requestand from webmethod. I will return a single JSON string.

How can I use this on an HTML page using an Ajax post request. I want to know what all the changes I need to make for the web method to accept a JSON String.

public class Hello { @POST public String sayPlainTextHello() { return "Hello Jersey"; } } 
+7
source share
2 answers

You need to break your requests. First, you want to accept a JSON string. So, according to your method, you need

 @Consumes(MediaType.APPLICATION_JSON) 

Then you need to decide what you want to receive. You can get the JSON string as you suggest, in which case your method would look like this:

 @Consumes(MediaType.APPLICATION_JSON) public String sayPlainTextHello(final String input) { 

Or, if your JSON string maps to a Java object, you can directly take the object:

 @Consumes(MediaType.APPLICATION_JSON) public String sayPlainTextHello(final MyObject input) { 

You state that you want to return a JSON string. Therefore you need to:

 @Produces(MediaType.APPLICATION_JSON) 

And then you need to actually return the JSON string:

 return "{\"result\": \"Hello world\"}"; 

So your complete method looks something like this:

 @PATH("/hello") @POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public String sayPlainTextHello(final String input) { return "{\"result\": \"Hello world\"}"; } 

As for using AJAX to send and receive, it will look something like this:

 var myData="{\"name\": \"John\"}"; var request = $.ajax({ url: "/hello", type: "post", data: myData }); request.done(function (response, textStatus, jqXHR){ console.log("Response from server: " + response); }); 
+26
source

That will work. "path" is the relative URL path to be used in the AJAX call.

 public class Hello { @POST @Path("/path") @Produces({ "text/html" }) public String sayPlainTextHello() { return "Hello Jersey"; } 

}

0
source

All Articles