weixin_33743248 2016-12-08 15:51 采纳率: 0%
浏览 110

JAX-RS获取主体参数

In javascript I am making an ajax post request to one of my JAX-RS functions like this

 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. 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. Here is how I am sending it

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

1条回答 默认 最新

  • weixin_33714884 2016-12-08 16:13
    关注

    Lets say your method is supposed to handle GET request like below

        @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. It may be PathParam and several others as well. Only one argument is allowed which is not annoatated in JAX-RS. Let's say you have User object like below:

        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. In case you are using Json you will need explicit MessageBodyReader for it.

    评论

报告相同问题?

悬赏问题

  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染