【问题标题】:Rest jax-rx web-service don't get data from Html-form+JQueryRest jax-rs web-service 不从 Html-form+JQuery 获取数据
【发布时间】:2017-06-12 10:58:11
【问题描述】:

我有带有 Spring Boot、JQuery、Html 模板 jn WildFly 10 的 Jax-rs 和 我的 @Post 和 @Put 方法从 Html 表单中获取 null。

客户资源:

@POST
    //@Path("/create")
    @Consumes(MediaType.APPLICATION_JSON)
    public Response createCustomers(@QueryParam("firstname") String firstname,
                                    @QueryParam("lastname") String lastname,
                                    @QueryParam("email") String email,
                                    @QueryParam("dateborn") String dateborn,
                                    @QueryParam("pass") String pass,
                                    @Context UriInfo uriInf
    ){
        CustomersEntity customer = new CustomersEntity();
        customer.setFirstname(firstname);
        customer.setLastname(lastname);
        customer.setEmail(email);
        customer.setDateborn(dateborn);
        customer.setPass(pass);
        customerService.save(customer);
        long id = customer.getId();

        URI createdUri = uriInf.getAbsolutePathBuilder().path(Long.toString(id)).build();
        return Response.created(createdUri).build();
    }

    @PUT
    @Path("/{id}")
    @Consumes(MediaType.APPLICATION_JSON)
    public Response updateCustomers(@PathParam("id") Long id,

                                @QueryParam("customerFn") String firstname,
                                    @QueryParam("customerLn") String lastname,
                                    @QueryParam("customerEmail") String email,
                                    @QueryParam("customerDb") String dateborn,
                                    @QueryParam("customerPass") String pass
                                   ) {
        CustomersEntity inDb = customerService.findOne(id);
        if (inDb == null){
            throw new WebApplicationException(Response.Status.NOT_FOUND);
        }
        else {
        inDb.setFirstname(firstname);
        inDb.setLastname(lastname);
        inDb.setEmail(email);
        inDb.setDateborn(dateborn);
        inDb.setPass(pass);
        customerService.update(inDb);
        }
        return Response.noContent().build();
    }

HTML 格式:

<form id="customerForm" method="POST" action="/customers">

        <div class="mainArea">

            <label>Id:</label>
            <input id="custId" name="id" type="text" disabled="disabled" />

            <label>First Name:</label>
            <input type="text" id="custFn" name="customerFn" required="required" />

            <label>Last Name:</label>
            <input type="text" id="custLn" name="customerLn" />

            <label>Email:</label>
            <input type="text" id="custEmail" name="customerEmail" />

            <label>Date Born:</label>
            <input type="text" id="custDb" name="customerDb" />

            <label>Pass:</label>
            <input type="text" id="custPass" name="customerPass" />

            <button id="btnSaveCustomer">Save</button>
            <button id="btnDeleteCustomer">Delete</button>
        </div>
    </form>

JQuery:

function addCustomer() {
    console.log('addCustomer');
    $.ajax({
        type: 'POST',
        contentType: 'application/json',
        url: customerlistURL,// + '/create',
        dataType: "json",
        data: formToJSON(),
        success: function(data, textStatus, jqXHR){
            alert('Customer created successfully');
            $('#btnDeleteCustomer').show();
            $('#custId').val(data.id);
        },
        error: function(jqXHR, textStatus, errorThrown){
            alert('addCustomer error: ' + textStatus);
        }
    });
}

function updateCustomer() {
    console.log('updateCustomer');
    $.ajax({
        type: 'PUT',
        contentType: 'application/json',
        url: customerlistURL + '/' + $('#custId').val(),
        dataType: "json",
        data: formToJSON(),
        success: function(data, textStatus, jqXHR){
            alert('Customer updated successfully');
        },
        error: function(jqXHR, textStatus, errorThrown){
            alert('updateCustomer error: ' + textStatus);
        }
    });
}

function deleteCustomer() {
    console.log('deleteCustomer ' + $('#custId').val());
    $.ajax({
        type: 'DELETE',
        url: customerlistURL + '/' + $('#custId').val(),
        success: function(data, textStatus, jqXHR){
            alert('Customer deleted successfully');
        },
        error: function(jqXHR, textStatus, errorThrown){
            alert('deleteCustomer error');
        }
    });
}

在这个配置中我得到下一个错误: (@POST):

Caused by: org.postgresql.util.PSQLException: ERROR: null value in column "email" violates not-null constraint
  Подробности: Failing row contains (8, null, null, null, null, null).
    at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2455)
    at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2155)
    at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:288)
    at org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:430)
    at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:356)
    at org.postgresql.jdbc.PgPreparedStatement.executeWithFlags(PgPreparedStatement.java:168)
    at org.postgresql.jdbc.PgPreparedStatement.executeUpdate(PgPreparedStatement.java:135)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.tomcat.jdbc.pool.StatementFacade$StatementProxy.invoke(StatementFacade.java:114)
    at com.sun.proxy.$Proxy152.executeUpdate(Unknown Source)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:204)
    ... 159 more

在@PUT 中也一样

@DELETE 和所有 @GET 方法都可以正常工作。

我尝试将@FormParam 与/或@Consumes(MediaType.APPLICATION_JSON)/@Consumes(MediaType.AP‌​‌​PLICATION_FORM_URL‌​EN‌​CODED) 一起使用,我在这两种情况下都采用:“PUT localhost:8080/animals-休息/索引/客户/2 415(不支持的媒体类型)”。或者:“当请求实体的内容类型不是 application/x-www-form-urlencoded 时使用@FormParam”。不,我需要一件 JAX-RS 球衣,不是别的。

【问题讨论】:

    标签: spring-boot jax-rs jersey-2.0 forms http-post


    【解决方案1】:

    您在 html 中使用 POST 方法并使用 @QueryParam 访问它,这将为空,因为收到的 http 请求没有任何查询参数。您可以使用@FormParam 来访问参数。或者在春天像下面这样:

     @RequestMapping("createCustomer", method="RequestMethod.POST")
     public Response createCustomers(@ModelAttribute("customerForm") Customer customer)
    

    请查看以下链接以使用 FormParam:using @FormParam

    检查requestParam和formParam的区别: difference between formParam and queryParam

    使用 spring 具有很多内置功能,因此您无需单独获取单个参数。请按照 jquery 的一些关于 spring 的好教程。

    【讨论】:

      【解决方案2】:

      经过对这个问题的一些思考和研究,我找到了答案。 Jax-rs Jarsey2 配置从请求正文中提取数据和数据格式,无需使用额外的注释从 HTML-form 转换:

      @PUT
      @Path("{id}")
      @Consumes(MediaType.APPLICATION_JSON)
      public Response updateCustomers(@PathParam("id") Long id,
                                      CustomersEntity customer){
          CustomersEntity existCustomer = customerService.findOne(id);
          if (existCustomer == null){
              throw new WebApplicationException(Response.Status.NOT_FOUND);
          }
          else {
              existCustomer.setFirstname(customer.getFirstname());
              existCustomer.setLastname(customer.getLastname());
              existCustomer.setEmail(customer.getEmail());
              existCustomer.setDateborn(customer.getDateborn());
              existCustomer.setPass(customer.getPass());
              customerService.update(customer);
          }
          return Response.noContent().build();
      }
      

      【讨论】:

        猜你喜欢
        • 2016-08-22
        • 2016-07-27
        • 1970-01-01
        • 2016-12-06
        • 1970-01-01
        • 1970-01-01
        • 2012-09-09
        • 2015-02-03
        • 2018-12-17
        相关资源
        最近更新 更多