【问题标题】:Rest service adding an extra parameter throws error休息服务添加额外的参数会引发错误
【发布时间】:2020-11-10 07:41:50
【问题描述】:

我正在尝试使用正文创建 REST 服务。当我尝试添加一个额外的参数(以读取 POST 正文)时,不会调用其余请求。

第一个 JAVA 类:

@Path("{module}/{messageKey}")
    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public Response status(final @Context HttpServletRequest request, @PathParam("module") final String module, @PathParam("messageKey") final String messageKey, final GetMessageDAO dao) {
        String messageText = "";
System.out.println(messageKey);
        CacheControl cacheControl = new CacheControl();
        cacheControl.setNoCache(true);
        return Response.ok(String.valueOf(messageText)).cacheControl(cacheControl).build();
    }

第二个 Java 类:

public class GetMessageDAO {

    @JsonProperty("args")
    private String args;

    public String getArgs() {
        return args;
    }

    public void setArgs(String args) {
        this.args = args;
    }
}

JS 调用:

    new Ajax.Request(
          '/ecmws/resources/message/gp/transactionManager.confirm.affected_calc_req', 
          {
            method: 'post',
            parameter: {args: "abc"},
data: {args: "abc"},
            contentType: 'application/json;charset=UTF-8',
            charset: 'UTF-8',
            async: false});

当我从第一个 Java 类中删除最后一个参数时,它工作正常,但我还需要读取 POST 正文,因此问题。

我在类路径中有 jersey-core、jersey-json、jersey-client、jersey-server、jackson-mapper。

你能建议我缺少什么吗?

【问题讨论】:

  • 你的班级是如何注册的?你有@ApplicationPath ResourceConfig 类吗?

标签: java json rest jersey


【解决方案1】:

不是您的 Jersey Controller 问题,而是您在 AJAX 调用中发送数据的方式。

如果您发出 postman 调用或 curl 您的请求,您可能不会遇到任何问题,即使使用 GetMessageDAO 的方法也会按预期调用。但是从浏览器进行 ajax 调用会失败。

curl --request POST 'http://localhost:8080/todos/hello/world' --header 'Content-Type: application/json' --data-raw '{"args":"b"}' 

要解决此问题,请更改您的线路

data: {args: "abc"},

data: JSON.stringify({args: 'abc'}),

进一步(验证):

如果您检查您的浏览器网络请求,数据没有 JSON.stringify 发送为

args=abc

但将其更改为 JSON.stringify 会将其更改为 JSON String,您将看到正在发送的数据是:

{"args": "abc"}

然后可以将其编组到GetMessageDAO 类实例。

【讨论】:

    【解决方案2】:

    如果您关注jersey example project,您必须拥有扩展ResourceConfig 的应用程序类,其中应包括您的类和JacksonFeature

    public class MyApplication extends ResourceConfig {
         public MyApplication() {
            super(
               EmptyArrayResource.class,
               NonJaxbBeanResource.class,
               CombinedAnnotationResource.class,
               // register Jackson ObjectMapper resolver
               MyObjectMapperProvider.class,
               ExceptionMappingTestResource.class,
               JacksonFeature.class
       );
    

    【讨论】:

      【解决方案3】:
      • 在您的应用程序中,预先实例化您的 GetMessageDAO 类(任何 DAO 类)并将其作为“第一个 Java 类”的构造函数参数传递。
      • 在“1st Java class”的构造函数中,将GetMessageDAO设置为字段变量
      • 在方法status 中,访问字段变量。

      【讨论】:

        【解决方案4】:

        jersey-media-json-jackson denepndency 添加到您的项目中。

        它是 JSON Jackson 的支持模块。

        【讨论】:

          【解决方案5】:

          您是否考虑过使用@FormParam@BeanForm 注释:

          @POST
          public String delivery(@FormParam("deliveryAddress") String deliveryAddress,
                                 @FormParam("quantity") Long quantity) 
          {
              return "Form parameters are " +
                      "[deliveryAddress=" + deliveryAddress + ", quantity=" + quantity + "]";
          }
          

          您需要设置正确的 Content-Type 来模拟表单提交操作。 \

          要设置表单参数,请使用 -d 标志:

          curl -X POST -H 'Content-Type:application/x-www-form-urlencoded' \
             -d 'deliveryAddress=Street 1A&quantity=5' \
             http://localhost:8080/application/delivery
          

          输出:

          Form parameters are [deliveryAddress=Street 1A, quantity=5]
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2020-04-10
            • 1970-01-01
            • 2012-11-16
            相关资源
            最近更新 更多