【问题标题】:jQuery not POSTing URL arguments to Jersey service?jQuery 没有向 Jersey 服务发布 URL 参数?
【发布时间】:2013-08-05 13:57:22
【问题描述】:

这看起来很简单,但我不知道为什么它不起作用。

我定义了 Jersey 服务:

@POST
public SomeObject createSomeObject(
    @QueryParam("firstParam") String firstParam,
    @QueryParam("secondParam") String secondParam)
{
    // Does stuff, returns the object.
}

现在,如果我做一个简单的curl,它可以正常工作:

curl -X POST "http://localhost:8080/path/to/service?firstParam=Bleh&secondParam=Blah

但是,对于 Java 中的 firstParam 和 secondParam,以下结果为 null

$.ajax({
    url: '/path/to/service',
    type: 'POST',
    data: {
        firstParam: 'Bleh',
        secondParam: 'Blah'
    },
    success: doStuff,
    error: eek
});

这看起来非常简单。我觉得他们应该表现得完全一样。我错过了什么?我尝试过的事情(但似乎没有必要):

  • contentType: 'application/x-www-form-urlencoded' 添加到ajax 调用中。
  • @Consumes(MediaType.APPLICATION_FORM_URLENCODED) 添加到 Jersey 服务。
  • JSON.stringify 包装数据对象(我知道在contentType: 'json' 时我需要这样做,但不应该在这里。

我知道我可以自己编写 URL 参数并将它们填充到 URL 中,但这似乎不优雅,我不应该这样做。

【问题讨论】:

    标签: jquery ajax jersey


    【解决方案1】:

    如果您使用 POST 发送多个参数,则必须执行 application/x-www-form-urlencoded POST,这样参数在请求中编码如下:

    firstParam=Bleh&secondParam=Blah
    

    但是,要使用这些参数,您必须注释函数参数,例如:

    @POST
    public SomeObject createSomeObject(@FormParam("firstParam") String firstParam,
                                       @FormParam("secondParam") String secondParam) {
        // Does stuff, returns the object.
    }
    

    注意注解是@FormParam 而不是@QueryParam

    请注意,如果您执行“普通” POST,您的函数只能有一个参数来接收 de POST 数据(除了从查询字符串 url 参数分配的参数)

    【讨论】:

    • 有趣。我从来不知道@FormParam。等我回家确认后再试试!谢谢!
    【解决方案2】:
    $.ajax({
            type: "POST",
            contentType: "application/x-www-form-urlencoded;charset=utf-8",
            url: url,
            data: data,
            dataType: 'json',
            timeout: 3000,
            // jsonpCallback:"foo",
            success:function(response){
                console.log(response);              
            },
            error: function(){
                console.log("error!");
            }
        });
    

    上面是一个 jquery 请求,正如@futuretelematics 所说,我们需要 contentType:“application/x-www-form-urlencoded;charset=utf-8”。 然后在 Jersey 服务中添加@Consumes({MediaType.APPLICATION_FORM_URLENCODED})。

    @POST
    @Produces({ MediaType.APPLICATION_JSON})
    @Consumes( {MediaType.APPLICATION_FORM_URLENCODED})
    public String execute(@FormParam("stoYardName") String data,
                           @FormParam("domTree") String domTree
                                        ) {
                .........
    

    };

    【讨论】:

      猜你喜欢
      • 2011-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-19
      • 1970-01-01
      相关资源
      最近更新 更多