本文作者:佚名

springmvc 日期提交报400错误的解决

佚名 2019-05-18 ???
摘要:其实这个大家都知道了,就我不知道:在BaseController 中增加:@InitBinderprotected void initBinder(WebDataBinder binder) {/


其实这个大家都知道了,就我不知道:

在BaseController 中增加:

	@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()).replace("·", "·"));
			}
			@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));
			}
			@Override
			public String getAsText() {
				Object value = getValue();
				return value != null ? DateUtils.formatDateTime((Date)value) : "";
			}
		});
	}

 其他格式的,如果出错,请参照下面的代码:

import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import sun.beans.editors.DoubleEditor;
import sun.beans.editors.FloatEditor;
import sun.beans.editors.IntEditor;
import sun.beans.editors.LongEditor;

@Controller
public class BaseController {

    @InitBinder    
    public void initBinder(WebDataBinder binder) {    

        binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true)); 
        binder.registerCustomEditor(int.class, new IntEditor());
        binder.registerCustomEditor(long.class, new LongEditor());  
        binder.registerCustomEditor(double.class, new DoubleEditor());  
        binder.registerCustomEditor(float.class, new FloatEditor());  
    }
    
    
}

未经允许不得转载:

作者:佚名,标题:springmvc 日期提交报400错误的解决,原文地址:https://www.vfjianzhan.com/android/201905/19.html发布于2019-05-18
转载或复制请以超链接形式并注明出处唯福建站

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏