Spring MVC "The request sent by the client was syntactically incorrect ()"解决办法

今天在做前台form表单提交的时候,遇到了一个问题,后台无任何反应。


The request sent by the client was syntactically incorrect :客户端发送的请求有语法错误。

查了下log日志,发现是因为form表单中存在一个日期,表单提交的时候,spring转换日期(由String转为Date)出错了!

解决办法:

Customizing WebDataBinder initialization 
To customize request parameter binding with PropertyEditors, etc. via Spring's WebDataBinder, you can either use @InitBinder-annotated methods within your controller or externalize your configuration by providing a custom WebBindingInitializer. 

Customizing data binding with @InitBinder 
Annotating controller methods with @InitBinder allows you to configure web data binding directly within your controller class. @InitBinder identifies methods which initialize the WebDataBinder which will be used for populating command and form object arguments of annotated handler methods. 
Such init-binder methods support all arguments that @RequestMapping supports, except for command/form objects and corresponding validation result objects. Init-binder methods must not have a return value. Thus, they are usually declared as void. Typical arguments include WebDataBinder in combination with WebRequest or java.util.Locale, allowing code to register context-specific editors. 

可以在Controller 中添加:

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

WebDataBinder是用来绑定请求参数到指定的属性编辑器,可以继承WebBindingInitializer来实现一个全部controller共享的dataBiner 

@Component
public class CommonBindingInitializer implements WebBindingInitializer {

    public void initBinder(WebDataBinder binder, WebRequest request) {
        SimpleDateFormat dateFormat = new SimpleDateFormat(ERPUtil.ISO_DATE_MASK);
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
        binder.registerCustomEditor(String.class, new StringTrimmerEditor(false));
    }
}

还可以通过spring mvc 的注解 @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) 来解决。




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值