- Spring 400 Bad Request
报错:浏览器用ajax的POST请求到Spring后台报错400 (Bad Request)
原因:出现这个错误的原因一般最常见的就是后台的实体类bean与前台传过来的类型不匹配,我的是后台某个String类型的参数在前台js传过来时没有用引号“”包裹,导致前后台类型不匹配。
解决:针对我的情况,我将该参数用“”包裹后成功传到后台匹配。
其他这个错误的情况参考下面这篇博文:SpringMVC中出现” 400 Bad Request “错误(用@ResponseBody处理ajax传过来的json数据转成bean)的解决方法
- String类型参数直接用@RequestBody注解会报解析错误
报错:xxx方法(@RequestBody String id)
会报错
解决:可以用xxx(@RequestBody Map<String, Object> datas)
,然后从datas中获取参数值datas.get("id")
,再转换相应类型。
- Mybatis关联查询延迟加载报错
报错:
com.fasterxml.jackson.databind.JsonMappingException: No serializer found for class org.apache.ibatis.executor.loader.javassist.JavassistProxyFactory$EnhancedResultObjectProxyImpl and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) )
原因:使用mybatis的<collection>
或<association>
标签时,存在“延迟加载”这个概念。 如果一个实体类的某个属性是其它实体类的类型,且项目中使用了延迟加载(mybatis默认使用了 延迟加载),这就会出现在处理类时,它的属性还没有被序列化,导致如上bug的出现。
解决:
在主动关联的实体类(并非是作为属性的实体类 )的类头(接口头)上加上@JsonIgnoreProperties(value = {"handler"})
注解
如在下面例子中的Recommend类上加注解:
<resultMap type="com.zz.model.Recommend" id="mRecommend">
<id property="id" column="rec_id"/>
<result property="title" column="rec_title"/>
<association property="user" javaType="com.zz.model.Muser" column="rec_userId" select="getMuser">
</association>
</resultMap>
//json序列化时忽略bean中的一些属性序列化和反序列化时抛出的异常
@JsonIgnoreProperties(value = {"handler"})
@TableName("recommend")
public class Recommend implements Serializable {
……
/**
* @备注:推荐人id
* @字段:user_id BIGINT(19)
*/
private java.lang.Long userId;
/**
* 备注:推荐人(并非数据库中的字段)
*/
@TableField(exist = false)
……
}
其他解法(自定义 com.fasterxml.jackson.databind.ObjectMapper 类):
Spring MVC 解决 Could not write JSON: No serializer found for class java.lang.Object
Spring and jackson, how to disable FAIL_ON_EMPTY_BEANS through @ResponseBody
- 前台传日期字符串到SpringMVC报400错误
解决:加入对应格式(如yyyy-MM-dd HH:mm:ss)的时间格式化注解@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss" )
/**
* @备注:开始日期
* @字段:start_date DATETIME(19)
*/
@JsonSerialize(using=DateJsonSerializer.class)
@JsonDeserialize(using=DateJsonDeserializer.class)
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss" )
private java.util.Date startDate;
/**
* @备注:结束日期
* @字段:end_date DATETIME(19)
*/
@JsonSerialize(using=DateJsonSerializer.class)
@JsonDeserialize(using=DateJsonDeserializer.class)
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss" )
private java.util.Date endDate;