Spring MVC数据绑定400错误 Myth丶恋晨 2022-10-01 00:50 128阅读 0赞 ![Center][] 错误如图,客户端的请求有语法错误,则意味着数据绑定出现了问题 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的转换了 [Center]: /images/20220705/b00897ae252f477f850b782a70cb646e.png
还没有评论,来说两句吧...