前台JSON数据传送数据到后台,报400错误怎么解决

如题所述

原因:
在SpringMVC中的Action中处理前台ajax请求传过来的json数据直接转成对应的实体类时出错:400 Bad Request,后台也不报错,400指的的是请求无效(请求有语法问题或者不能满足请求)。
1:一般最常见的就是后台的实体类bean与前台穿过的类型不匹配,如你的javabean中有定义了Date类型和int类型的成员变量,导致转化器在把json数据转化成bean时不能转化。
2:log4j的配置文件里错误将部分log打为Info级别所致
3:要返回json的却忘了加@ResponseBody
4:ajax请求的连接后边忘了加参数,如url:basePath + "kscj/unbill.do?jqid="+jqids

5:传了非实体bean属性的参数过来。
6:controller指定的参数名称与前台不一致,如:使用了@RequestParam(value="userName")而前台必须指定该名称

@RequestMapping("/hello.do")
public String hello(HttpServletRequest req,HttpServletResponse resp,@RequestParam(value="userName")String user ){
request.setAttribute("user", user);
return "hello";
}

也可以指定该参数是非必须的required=false,如:

@RequestMapping("/hello.do")
public String hello(HttpServletRequest req,HttpServletResponse resp,@RequestParam(value="userName",required=false)String user){
request.setAttribute("user", user);
return "hello";
}

解决方法:
1:把实体类的javabean里边的类型都改成string类型,在配置SQL语句时用数据库函数to_date或者to_number转化的,如果再java中用到这个字符串类型的日期的话,有必要的话,就用For format=new SimpleDateFormat("yyyy-MM-dd"),format.parse()来转换。
2:在对应的实体类的对应的非字符串类型的变量的setter方法中传入string类型的,然后在里边用SimpleDateFormat或者Integer进行转化。
温馨提示:答案为网友推荐,仅供参考
第1个回答  2017-08-04
用字符串接收,然后再转为json处理
相似回答