博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
SpringMvc 数据绑定400错误
阅读量:6984 次
发布时间:2019-06-27

本文共 1942 字,大约阅读时间需要 6 分钟。

今天请求一个SpringMvc 的时候,客户端总是报出:

The request sent by the client was syntactically incorrect

网上都是说的是bean的名字和表单的名字不一样,但是我检查了N多遍之后,还是有报这个异常,就想到了SpringMvc 自动装配的问题。

然后看日志说是""转为int类型的时候不可以为空;

应该就是数据绑定的问题了,经过一番研究,springMvc的数据绑定有几种方式:

1,controller 独享

2,全局共享

controller独享方式:

@InitBinderpublic void initBinder(WebDataBinder binder) {    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");    dateFormat.setLenient(false);    binder.registerCustomEditor(Date.class, new CustomDateEditor(            dateFormat, false));}

全局共享:        

全局共享方式有几种实现方法:

继承 WebBindingInitializer 接口来实现全局注册

使用@InitBinder只能对特定的controller类生效,为注册一个全局的customer Editor,可以实现接口WebBindingInitializer 。

 

public class CustomerBinding implements WebBindingInitializer {    @Override    public void initBinder(WebDataBinder binder, WebRequest request) {        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");        dateFormat.setLenient(false);        binder.registerCustomEditor(Date.class, new CustomDateEditor(                dateFormat, false));    }

xml配置文件:

 

 

使用conversion-service来注册自定义的converter  

DataBinder实现了PropertyEditorRegistry, TypeConverter这两个interface,而在spring mvc实际处理时,返回值都是return binder.convertIfNecessary(见HandlerMethodInvoker中的具体处理逻辑)。因此可以使用customer conversionService来实现自定义的类型转换。

配置文件:

实现类:

public class LongConverter implements Converter
{ @Override public Long convert(String text) { if (StringUtil.isEmpty(text))return 0l; try { return Long.parseLong(text); } catch (Exception e) { // TODO: handle exception } return 0l; }}

xml配置converter:

 

转载于:https://www.cnblogs.com/tony-jingzhou/p/3726164.html

你可能感兴趣的文章
PhotoShop常用的功能汇总
查看>>
基于移动端Reactive Native轮播组件的应用与开发详解
查看>>
专家的修炼之路 —— 德雷福斯模型 Dreyfus
查看>>
TcpClient和TcpListener 类的使用-编写一个点对点聊天工具(初级入门篇)
查看>>
CSS 圆角
查看>>
C#解压缩文件
查看>>
Golang学习笔记——Slice
查看>>
ERDAS软件应用(三)遥感图像的拼接
查看>>
在面试中如何展示虚拟机和内存调优技能
查看>>
hdu 1534 Schedule Problem (差分约束)
查看>>
HDU1159 Common Subsequence【最长公共子序列】
查看>>
C++ 字符数组函数与string函数
查看>>
无限极分类优化方式
查看>>
从运维的角度理解Iaas、Paas、Saas云计算
查看>>
使用动画播放文件夹中的图片
查看>>
logging模块
查看>>
C# 将string 转换为二维码图片,然后转为base64字符串编码 。
查看>>
软件工程概论03
查看>>
js截取最后一个斜杠之后的内容
查看>>
Java程序安装失败
查看>>