使用Spring Boot @POST方法的Jax-rs(jersey2) - 400错误

时间:2017-06-28 11:16:57

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

我有Jax-rs,Spring Boot + JPA,PostgreSQL,JQuery,当尝试在@POST请求中创建客户时,我得到400错误。所有@ GET和@PUT都能正常工作 这是资源方法:

@Path("/customers")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class CustomerResource {

    @Autowired
    private CustomerService customerService;

...

@POST
    public Response createCustomers(CustomersEntity customer,
                                    @Context UriInfo uriInfo
    ){
        customerService.save(customer);
        Long id = customer.getId();

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

JQuery的:

function addCustomer() {
    console.log('addCustomer');
    //add CSRF AJAX/REST protection:
    //csrfGet.make();
    $.ajax({
        type: 'POST',
        contentType: 'application/json',
        url: customerlistURL,
        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);
        }
    });
}

formToJSON():

function formToJSON() {
    var customerId = $('#custId').val();
    return JSON.stringify({
        "id": customerId == "" ? null : customerId,
        "firstname": $('#custFn').val(),
        "lastname": $('#custLn').val(),
        "email": $('#custEmail').val(),
        "dateB": $('#custDb').val(),
        "pass": $('#custPass').val()
    });
}

当我在POST方法中尝试创建时,我得到了这个标题:

    * Request URL:http://localhost:8080/index/customers

        * Request Method:POST

        * Status Code:400 

        * Remote Address:[::1]:8080

        * Referrer Policy:no-referrer-when-downgrade

    * Response Headersview source

        * Connection:close

        * Date:Wed, 28 Jun 2017 10:57:44 GMT

        * Server:Apache-Coyote/1.1

        * Transfer-Encoding:chunked

    * Request Headersview source

        * Accept:application/json, text/javascript, */*; q=0.01

        * Accept-Encoding:gzip, deflate, br

        * Accept-Language:ru-RU,ru;q=0.8,en-US;q=0.6,en;q=0.4

        * Connection:keep-alive

        * Content-Length:120

        * Content-Type:application/json

        * DNT:1

        * Host:localhost:8080

        * Origin:http://localhost:8080

        * Referer:http://localhost:8080/

        * User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) 
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36

        * X-Requested-With:XMLHttpRequest

    * Request Payloadview source

            * {id: null, firstname: "fn-test1", lastname: "ln-test1", email: "email-test1", dateB: "db-test1",…}

                * dateB: "db-test1"
        

email: "email-test1"
        

firstname: "fn-test1"
        

id: null
        

lastname: "ln-test1"
        

pass: "testTEST12345"
        

我在POST方法中做错了什么?

1 个答案:

答案 0 :(得分:0)

方法按预期工作。问题出在测试数据中。 所以当我写这样的东西时,我在服务器日志中看到了它:

 @POST
        public void createCustomer(InputStream in){
            CustomersEntity customer = readCustomer(in);
            System.out.println(customer.toString());
            customer.setId(idCounter.incrementAndGet());
            customerDB.put(customer.getId(), customer);
            System.out.println("Created customer " + customer.getId());
            System.out.println(customerDB);
            customerService.save(customer);
}

protected CustomersEntity readCustomer(InputStream in) {
        ObjectMapper mapper = new ObjectMapper();
        CustomersEntity customer = new CustomersEntity();
        try {
            customer = mapper.readValue(in, CustomersEntity.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return customer;
    }


private Map<Long, CustomersEntity> customerDB =
            new ConcurrentHashMap<Long, CustomersEntity>();
    private AtomicLong idCounter = new AtomicLong();