简体   繁体   English

JAX-RS获取主体参数

[英]JAX-RS get body parameters

In javascript I am making an ajax post request to one of my JAX-RS functions like this 在javascript中,我向这样的JAX-RS函数之一发出了ajax发布请求

 var postPackingListRequest = $http({
              method: "post",
              url: "/rest/v1/submit",
              data: $scope.items
          });

And now in my JAX-RS method I am trying to get the varibale $scope.items that was passed. 现在,在我的JAX-RS方法中,我试图获取通过的变量$scope.items I know I can get path params in the path like this 我知道我可以在这样的路径中获取路径参数

public Response getPathParams(@QueryParam("id") int id) {

But how can I get the data, which is passed in the body? 但是,如何获取在体内传递的数据呢?

Thanks 谢谢

EDIT 编辑

@POST
@Path("submit")
@Consumes(MediaType.APPLICATION_JSON)
@ApiResponses({ @ApiResponse(code = 201, response = Response.class) })
@Produces("application/json")
public Response submitPackingList(TestUser testUser) {

}

public class TestUser {
    public String id;
    public String name;
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

When I send a request to this with the TestUser there I am getting a HTTP 400 error. 当我通过TestUser发送请求时,出现HTTP 400错误。 Here is how I am sending it 这是我发送的方式

var postPackingListRequest = $http({
              method: "post",
              url: "/rest/v1/submit",
              data: "{'user':'1', 'name':james}"
          });

Lets say your method is supposed to handle GET request like below 可以说您的方法应该像下面那样处理GET请求

    @GET
    public Response getPathParams(@QueryParam("id") int id)

Now in the above method every argument must be annotated with something. 现在,在上述方法中,每个参数都必须带有一些注释。 In your case it is QueryParam. 您的情况是QueryParam。 It may be PathParam and several others as well. 可能是PathParam,也可能是其他几个。 Only one argument is allowed which is not annoatated in JAX-RS. 仅允许一个在JAX-RS中未注释的参数。 Let's say you have User object like below: 假设您有如下所示的User对象:

    public class User{
    String userName;
    int userId;
    //getters and setters
    }

and you want to accept user details that are coming via body of request then your method signature would look like below: 并且您想接受通过请求主体传入的用户详细信息,则您的方法签名将如下所示:

    @GET
    public Response getPathParams(@QueryParam("id") int id, User user)

Depending upon what the above method consumes whether it be json or xml the request body will be converted to User object and will get bind to your argument. 根据上述方法消耗的内容是json还是xml,请求正文将转换为User对象并将绑定到您的参数。 In case you are using Json you will need explicit MessageBodyReader for it. 如果您使用的是Json,则需要显式的MessageBodyReader。

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

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