Spring MVC数据绑定400错误
来源:互联网 发布:如何学好c语言 编辑:程序博客网 时间:2024/06/06 01:18
错误如图,客户端的请求有语法错误,则意味着数据绑定出现了问题
public class User { private String name; private String lastname; private String password; private String detail; private Date birthDate; private String gender; private String country; private boolean nonSmoking;
此时出现该错误是因为bean中有Date类型的数据,但是Spring MVC并不能把前端的String类型转换为Date类型
解决办法:
1.使用注解
在bean中的Date字段上加如下注解
@DateTimeFormat(pattern = "yyyy-MM-dd")private Date birthDate;
同时在SpringMVC的配置文件中添加
xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"
<mvc:annotation-driven />
mvc声明用http://www.springframework.org/schema/mvc/spring-mvc.xsd这个文件来解析,如果使用上述注解,必须加标红的配置
上述注解的作用:
1)会自动注册DefaultAnnotationHandlerMapping与AnnotationMethodHandlerAdapter 两个bean,是spring MVC为@Controllers分发请求所必须的。
2)数据绑定支持,@NumberFormatannotation支持,@DateTimeFormat支持,@Valid支持,读写XML的支持(JAXB),读写JSON的支持(Jackson)
这样就可以了,简答到没朋友。
但是这个问题折磨了我好久,就是因为没写<mvc:annotation-driven />........
2.使用自定义参数绑定(converter转换器方式)
1)编写响应的converter,实现固定接口:
第一个参数是原始类型,第二个参数是转换后的类型public class CustomDateConverter implements Converter<String, Date> { @Override public Date convert(String s) { try { return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(s); } catch (ParseException e) { e.printStackTrace(); } return null; }}
2)在springmvc.xml配置文件配置格式化转换服务工厂bean:FormattingConversionServiceFactoryBean
<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"> <property name="converters"> <list> <bean class="xyz.zhulei.spring_mybatis.controller.convert.CustomDateConverter"/> </list> </property> </bean>
3)
<mvc:annotation-driven conversion-service="conversionService"/>
大功告成,就可以自动完成string到date的转换了
0 0
- spring mvc 数据绑定 400错误
- Spring MVC数据绑定400错误
- spring mvc数据绑定
- spring mvc数据绑定
- spring mvc数据绑定
- Spring MVC 数据绑定
- Spring MVC-数据绑定
- Spring MVC 自定义数据绑定 报http 406错误
- Spring MVC数据绑定大全
- Spring MVC数据绑定大全
- Spring MVC数据绑定大全
- Spring MVC数据绑定大全
- Spring MVC数据绑定大全
- Spring MVC数据绑定大全 .
- Spring MVC数据绑定大全 .
- Spring MVC数据绑定大全
- Spring MVC数据绑定大全
- Spring MVC数据绑定大全
- jQuery datatable获取当前页面,刷新时保存在当前页面
- PHP,C++ 通用加解密,需要md5,base64 支持
- GreenDao 3.2.0使用教程
- @Controller 和@RestController 的区别
- Eclipse错误:找不到或无法加载主类 解决办法
- Spring MVC数据绑定400错误
- android-partition分析
- QT学习之设置界面风格
- 安装xdebug时发现的一些问题
- Python标准库——collections模块的Counter类
- 世界最早提出微循环理论者:赵炳文与修瑞娟
- 『 Spark 』10. spark 应用程序性能优化|12 个优化方法
- 仿QQ聊天Listview横向拖动删除等操作
- jquery+Jcrop+servlet图片上传裁剪选择保存实例