休息 jax-rs 网络服务不从 Html-formJQuery 获取数据
Rest jax-rx web-service don't get data from Html-form+JQuery
我有带有 Spring Boot 的 Jax-rs,JQuery,Html 模板 jn WildFly 10 和
我的@Post 和@Put 方法从 Html-form.
中获取空值
客户资源:
@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 with/or @Consumes(MediaType.APPLICATION_JSON)/@Consumes(MediaType.AP PLICATION_FORM_URL EN CODED) 和我接受两种情况:"PUT localhost:8080/animals-rest/index/customers/2 415 (Unsupported Media Type)"。或者:"The @FormParam is utilized when the content type of the request entity is not application/x-www-form-urlencoded"。不,我需要一件 JAX-RS 球衣,而不是其他。
您正在 html 中使用 POST 方法并使用 @QueryParam 访问它,这将为空,因为接收到的 http 请求没有任何查询参数。您可以使用@FormParam 来访问参数。或者在 spring 中,如下所示:
@RequestMapping("createCustomer", method="RequestMethod.POST")
public Response createCustomers(@ModelAttribute("customerForm") Customer customer)
请检查下面link以使用 FormParam:using @FormParam
查看requestParam和formParam的区别:
difference between formParam and queryParam
使用 spring 有很多内置功能,因此您不必单独获取单个参数。请按照 spring 和 jquery.
上的一些很好的教程进行操作
经过对这个问题的反思和研究,我找到了答案。 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();
}
我有带有 Spring Boot 的 Jax-rs,JQuery,Html 模板 jn WildFly 10 和 我的@Post 和@Put 方法从 Html-form.
中获取空值客户资源:
@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 with/or @Consumes(MediaType.APPLICATION_JSON)/@Consumes(MediaType.AP PLICATION_FORM_URL EN CODED) 和我接受两种情况:"PUT localhost:8080/animals-rest/index/customers/2 415 (Unsupported Media Type)"。或者:"The @FormParam is utilized when the content type of the request entity is not application/x-www-form-urlencoded"。不,我需要一件 JAX-RS 球衣,而不是其他。
您正在 html 中使用 POST 方法并使用 @QueryParam 访问它,这将为空,因为接收到的 http 请求没有任何查询参数。您可以使用@FormParam 来访问参数。或者在 spring 中,如下所示:
@RequestMapping("createCustomer", method="RequestMethod.POST")
public Response createCustomers(@ModelAttribute("customerForm") Customer customer)
请检查下面link以使用 FormParam:using @FormParam
查看requestParam和formParam的区别: difference between formParam and queryParam
使用 spring 有很多内置功能,因此您不必单独获取单个参数。请按照 spring 和 jquery.
上的一些很好的教程进行操作经过对这个问题的反思和研究,我找到了答案。 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();
}