简体   繁体   中英

Sending JSON from Javascript to JAX-RS

I want to try sending JSON data using JQuery AJAX to JAX-RS Web Service but I'm facing a problem.

My method on JAX-RS consume JSON and produces JSON, but when I tried to send JSON data, my method doesn't receive any parameter. What I missed out?

Here what I've tried

function callApi(counter){
  var apiDat = {param1:counter};

  $.ajax({
      type: 'POST',
      url: 'http://localhost:8080/xdbg/webresources/generic/value',
      data: JSON.stringify(apiDat),
      crossOrigin: true,
      dataType: 'json',          
      contentType: 'application/json; charset=utf-8',
      crossDomain: true,
      success: function(data) {
          console.log(data);
      }
  });
}

$(function () { 
  callApi(123);
});

Please take a note, I'm using CORS for method invocation :

@Path("generic")
public class GenericResource implements ContainerResponseFilter{
@Context
private UriInfo context;

@Override
public void filter(final ContainerRequestContext requestContext,
                  final ContainerResponseContext cres) throws IOException {
  cres.getHeaders().add("Access-Control-Allow-Origin", "*");
  cres.getHeaders().add("Access-Control-Allow-Headers", "origin, content-type, accept, authorization");
  cres.getHeaders().add("Access-Control-Allow-Credentials", "true");
  cres.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
  cres.getHeaders().add("Access-Control-Max-Age", "1209600");
}

@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path("/value")
public String GetValue(
    @DefaultValue("") @QueryParam("param1") String param1
)throws Exception{ 
    System.out.println("value = " + param1);
    JSONObject outputJsonObj = new JSONObject();
    outputJsonObj.put("output", param1);         
    return outputJsonObj.toString();
} 

Here is JSON format :

{"output":"123"}

What I missed out? Thanks

Your JSON document is being sent in the Body request.

In your web-service endpoint, you're not retrieving the http body, only the query param, with, as per your example code, will always be empty.

What you must do is create a POJO class with only the output property, and annotate it with @XMLAnnotations, like above:

@XmlRootElement(name="payload")
public class Payload {

    @XmlElement(name="output")
    public string output;

}

And then, change your method call to receive the POJO as a parameter, like above:

@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path("/value")
public String GetValue(Payload param)throws Exception{

In this situation, the JAX-RS container will parse the Http Request Body and create a Payload object that will be injected in your method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM