其实这个大家都知道了,就我不知道:
在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()).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()); } }