The entity of the spring form contains the processing of the date type

    Using the springMVC form, if the bean contains Date type data, it cannot be bound without processing, and the server reports a 400 error.

    The solution is to add the @InitBinder annotation to the controller layer, and springMVC will register these editors before binding the form:

@InitBinder    
protected  void initBinder(WebDataBinder binder) {    //不需要返回值
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");    
    binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));    
}

   @InitBinder can also configure other property editors: CustomNumberEditor, CustomBooleanEditor, etc. to implement data binding.

    Looking at the source code of jeesite today, there is already an initialization data binding operation in BaseController, as long as the control layer inherits BaseController:

/**
* 初始化数据绑定
* 1. 将所有传递进来的String进行HTML编码,防止XSS攻击
* 2. 将字段中Date类型转换为String类型
*/
@InitBinder
protected void initBinder(WebDataBinder binder) {
	// String类型转换,将所有传递进来的String进行HTML编码,防止XSS攻击
	binder.registerCustomEditor(String.class, new PropertyEditorSupport() {
		@Override
		public void setAsText(String text) {
			setValue(text == null ? null : StringEscapeUtils.escapeHtml4(text.trim()));
		}
		@Override
		public String getAsText() {
			Object value = getValue();
			return value != null ? value.toString() : "";
		}
	});
	// Date 类型转换
	binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
		@Override
		public void setAsText(String text) {
			setValue(DateUtils.parseDate(text));
		}
	});
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325316238&siteId=291194637