简体   繁体   English

将JSON从Javascript发送到JAX-RS

[英]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. 我想尝试使用JQuery AJAX将JSON数据发送到JAX-RS Web服务,但遇到了问题。

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. 我在JAX-RS上的方法使用JSON并生成JSON,但是当我尝试发送JSON数据时,我的方法未接收任何参数。 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 : 请注意,我正在使用CORS进行方法调用:

@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 : 这是JSON格式:

{"output":"123"}

What I missed out? 我错过了什么? Thanks 谢谢

Your JSON document is being sent in the Body request. 您的JSON文档正在“正文”请求中发送。

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. 在您的Web服务端点中,您无需检索http正文,只有查询参数(根据示例代码)始终为空。

What you must do is create a POJO class with only the output property, and annotate it with @XMLAnnotations, like above: 您需要做的是创建仅具有输出属性的POJO类,并使用@XMLAnnotations对其进行注释,如上所示:

@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: 然后,更改您的方法调用以将POJO作为参数接收,如上所示:

@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. 在这种情况下,JAX-RS容器将解析Http请求主体并创建一个有效负载对象,该对象将被注入您的方法中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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