【问题标题】:@PUT and @Post in Jersey2Jersey2 中的 @PUT 和 @Post
【发布时间】:2017-06-23 05:39:23
【问题描述】:

我的配置 Spring Boot、JQuery、Html 模板 jn WildFly 10 中出现 415 错误。 @PUT 和@POST:

    @POST
    //@Path("/create")
    @Consumes(MediaType.APPLICATION_JSON)
    public Response createCustomers(@FormParam("firstname") String firstname,
                                    @FormParam("lastname") String lastname,
                                    @FormParam("email") String email,
                                    @FormParam("dateborn") String dateborn,
                                    @FormParam("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,

                                @FormParam("customerFn") String firstname,
                                    @FormParam("customerLn") String lastname,
                                    @FormParam("customerEmail") String email,
                                    @FormParam("customerDb") String dateborn,
                                    @FormParam("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');
        }
    });
}

我得到:

响应标头: 状态码:415 不支持的媒体类型 连接:保持活动 日期:2017 年 6 月 12 日星期一 15:33:06 GMT 服务器:WildFly/10 传输编码:分块 X-Powered-By: Undertow/1

例外:

Caused by: java.lang.IllegalStateException: The @FormParam is utilized when the content type of the request entity is not application/x-www-form-urlencoded.

其他方法(所有@GET-s 和@DELETE)都可以正常工作。

【问题讨论】:

    标签: spring-boot jax-rs jersey-2.0


    【解决方案1】:

    如错误消息中所述,您不能将@FormParamapplication/x-www-form-urlencoded 以外的内容类型一起使用。

    【讨论】:

    • 当我在 Html-form 中添加 enctype="application/x-www-form-urlencoded" 并更改 @Consumes(MediaType.APPLICATION_FORM_URLENCODED) 我得到了同样的错误。我做错了什么?
    • 我不知道。你确定这是同样的错误吗?
    • 是的,我总是遇到同样的错误。在 Html 中有或没有 @Consumes 和 enctype="application/x-www-form-urlencoded"。如果我尝试使用 @QueryParam("firstname")... 等,我得到“原因:org.postgresql.util.PSQLException:错误:“电子邮件”列中的空值违反非空约束Подробности:失败行包含(8,空,空,空,空,空)。”配置只看到“id”,没有别的。
    【解决方案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();
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-05-31
      • 1970-01-01
      • 1970-01-01
      • 2015-02-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多