1

I have Jax-rs with Spring Boot, JQuery, Html templates jn WildFly 10 and my @Post and @Put method get null from Html-form.

CustomerResource:

@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:

<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');
        }
    });
}

And in this configuration I get next 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

and same in @PUT

@DELETE and all @GET method work fine.

I tried to use @FormParam with/or @Consumes(MediaType.APPLICATION_JSON)/@Consumes(MediaType.AP‌​‌​PLICATION_FORM_URL‌​EN‌​CODED) and I take in both case: "PUT localhost:8080/animals-rest/index/customers/2 415 (Unsupported Media Type)". Or: "The @FormParam is utilized when the content type of the request entity is not application/x-www-form-urlencoded". No, I need a JAX-RS Jersey, not else.

Community
  • 1
  • 1
naut92
  • 103
  • 1
  • 13

2 Answers2

0

You are using the POST method in html and accessing it using @QueryParam which will be null because there is not any query parameter to the http request received. You may use @FormParam to access the Parameters. Or in spring like below:

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

Please check below link to use FormParam:using @FormParam

check the difference between requestParam and formParam: difference between formParam and queryParam

using spring have lot of inbuilt feature so you dont have get single parameters seperately. Please follow some good tutorial on spring with jquery.

Sangam Belose
  • 4,262
  • 8
  • 26
  • 48
0

After some reflection and study of this issue, I found the answer. Jax-rs Jarsey2 configuration extracts data and data-format from the request body no need to use additional annotations for conversion from the 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();
}
naut92
  • 103
  • 1
  • 13