你好,我想把xuhao这个类在前端通过ajax传递到后端的时候,出现了Bad Request的错误,也就是400错误。这是为什么呢。这是我通过浏览器的控制台的NetWork找到的错误信息,可是我并不知道我错在哪里。一串英文,我英文水平差,也不太看得懂。
error:"Bad Request"
message:"JSON parse error: Cannot construct instance of com.example.demo.other.xuhao
(although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('{"xuhao:"1}'); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of com.example.demo.other.xuhao
(although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('{"xuhao:"1}')↵ at [Source: (org.springframework.util.StreamUtils$NonClosingInputStream); line: 1, column: 1]"
path:"/querycp2"
status:400
先看看我的代码吧,我用到了SpringBoot+Thymeleaf+Redis+Mybatis这样的框架
这是前端部分的HTML代码
<div id="cp" th:each="cangpin,cangpinStat:${cangpinlist}">
<div id="stdlib" hidden="hidden" th:text="${cangpin.xuhao}" ></div>
<div id="cq" width="80%" height="auto">
<img th:src="${cangpin.path2}">
<p class="cqb" style="display:none" th:text="${cangpin.began}"></p>
<p class="cqd" style="display:none" th:text="${cangpin.num}"></p>
<p class="cqc"></p>
</div>
这是我的变量
var stdlib=$("#stdlib").text();
var stdio="{\"xuhao:\""+stdlib+"}";
console.log(stdio);
console.log(JSON.stringify(stdio));
发现我的stdio变量是把这个xuhao自己自行改成了json形式,发现stdio变量和经过JSON序列化的stdio变量都是正常的,正常显示的。
这是ajax代码
$.ajax({
type:'post',
url:'./querycp2',
async:true,
error:"重新请求",
dataType:'json',
contentType:"application/json",
data: JSON.stringify(stdio),
success:function (){},
Error:function () {}
})
在data里,我已经转成json了。querycp2是我当前网页的url的地址。由于是post,url后面就是quercp2,没有任何问号,没有任何拼接。再说,我也不知道url怎么写,url怎么拼接。大概post不需要拼接。
这里我是普通请求,没有任何的表单,没有表单,更别说表单的提交了。
这些都是前端和ajax,再看看后端的代码
@CrossOrigin
@RequestMapping("/querycp2")
@ResponseBody
public Model getCangpin2(Model mp,@RequestBody(required = false) xuhao Xuhao){
ArrayList<Cangpin> cps= reds.getResult();
for(int i=0;i<cps.size();i++) {
cps.get(i).setYuanjia(new DecimalFormat("#0.00").format(BigDecimal.valueOf(Double.valueOf(cps.get(i).getYuanjia()))));
cps.get(i).setXianjia(new DecimalFormat("#0.00").format(BigDecimal.valueOf(Double.valueOf(cps.get(i).getXianjia()))));
}
mp.addAttribute("cangpinlist", cps);
mp.addAttribute("xuhao",Xuhao);
System.out.println("序号"+mp.getAttribute("xuhao"));
return mp;
}
发现打印出的序号后面的变量显示的是空值,也就是null值。
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import java.io.Serializable;
@JsonIgnoreProperties({"hibernateLazyInitializer","handler"})
public class xuhao implements Serializable {
long xuhao;
public long getXuhao() {
return xuhao;
}
public void setXuhao(long xuhao) {
this.xuhao = xuhao;
}
}
这是我的xuhao类。这个类位于com.example.demo.other.xuhao这里。其中xuhao类只有一个属性,属性是long数据类型,也就是长整型变量。
我英语水平太差,看不懂那个出错信息是什么意思。我究竟是哪里错了,ajax会显示400错误,也就是Bad Request错误。为什么后端显示的变量(也就是xuhao)为空值,也就是null。这是为什么?为什么我的ajax不能把前端的数据传递到后端呢?这是为什么?