我在Spring框架上使用Postgres数据库创建了Web服务。我使用JpaRepository来操作我的数据库和Rest控制器。我尝试使用jquery将对象保存到我的数据库但是我收到错误。 我应该在jquery调用和rest控件中更改成功执行什么?
这是jquery调用
$.ajax({
url: 'http://localhost:8080/products',
type: "POST",
data: { "productName":"product", "amount": 123, "dateArrival": 1522345884907},
dataType: "json",
success: function (result) {
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
我在[{1}}
中使用保存对象到数据库的函数RestController
阅读httpEntity后的字符串
@RequestMapping(value = "/products", method = RequestMethod.POST
,consumes = MediaType.ALL_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public Product saveProduct(HttpEntity<String> httpEntity){
String json = httpEntity.getBody().trim().replaceAll("\uFFFD", "");
ObjectMapper mapper = new ObjectMapper();
Product product = null;
try {
product = mapper.readValue(json,Product.class);
} catch (IOException e) {
e.printStackTrace();
}
return service.save(product);
}
这是我的实体
productName=product&amount=123&dateArrival=1522345884907&_token=undefined
错误
@Entity
@Table(name = "Stock")
public class Product {
public Product() {
}
@Id
@GeneratedValue(generator = "increment")
@GenericGenerator(name = "increment", strategy = "increment")
private long id;
@Column(name = "Product_name", nullable = false, length = 25)
@JsonProperty("productName")
private String productName;
@Column(name = "Amount", nullable = false, length = 50)
private int amount;
@Column(name = "Arrival_date", nullable = false)
@Temporal(TemporalType.TIMESTAMP)
private Date dateArrival;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public Integer getAmount() {
return amount;
}
public void setAmount(Integer amount) {
this.amount = amount;
}
public Date getDateArrival() {
return dateArrival;
}
public void setDateArrival(Date dateArrival) {
this.dateArrival = dateArrival;
}
@Override
public String toString() {
return "Product{" +
"id=" + id +
", productName='" + productName + '\'' +
", amount=" + amount +
", dateArrival=" + dateArrival +
'}';
}
}
答案 0 :(得分:0)
您可以在从HttpRequest正文中读取后发布的字符串吗?
您也可以尝试在没有unicode字符替换的情况下运行它,即删除replaceAll("\uFFFD", "")
答案 1 :(得分:0)
您的输入字符串:
productName=product&amount=123&dateArrival=1522345884907&_token=undefined
不是JSON。虽然异常不是非常具体,但它确实表明第一个字符('p')是意外的; JSON需要以{
字符开头(可能有前导空格)。