首先自定义一个格式转换类(我们以Date格式为例)DateFormatEditor继承自PropertiesEditor:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import org.springframework.beans.propertyeditors.PropertiesEditor;
public class DateFormatEditor extends PropertiesEditor {
// 日期是否允许为空
private boolean isAllowEmpty;
// 日期格式
private String pattern;
public DateFormatEditor() {
super();
this.isAllowEmpty = true;
this.pattern = "yyyy-MM-dd";
}
public DateFormatEditor(String pattern, boolean isAllowEmpty) {
super();
this.isAllowEmpty = isAllowEmpty;
this.pattern = pattern;
}
public boolean isAllowEmpty() {
return isAllowEmpty;
}
public void setAllowEmpty(boolean isAllowEmpty) {
this.isAllowEmpty = isAllowEmpty;
}
public String getPattern() {
return pattern;
}
public void setPattern(String pattern) {
this.pattern = pattern;
}
@Override
public void setAsText(String text) throws IllegalArgumentException {
try {
if (text != null && !text.equals("")) {
SimpleDateFormat format = new SimpleDateFormat(pattern);
setValue(format.parse(text));
} else {
if (isAllowEmpty) {
setValue(null);
}
}
} catch (ParseException e) {
System.out.println("格式转换失败!");
setValue(null);
}
}
}
定义完了还是不能用,这里需要我们注册:
由于需要全局的格式化转换所以我们定义一个BaseController类:
import java.util.Date;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import spring.util.DateFormatEditor;
@Controller
public class BaseController {
@Autowired
protected HttpServletRequest request;
@Autowired
protected HttpServletResponse response;
@Autowired
protected HttpSession session;
@Autowired
protected ServletContext application;
@InitBinder
protected void initDate(WebDataBinder binder) {
binder.registerCustomEditor(Date.class, new DateFormatEditor("yyyy-MM-dd hh:mm:ss", true));
}
}
这样就把所有Date类型的参数全部拦截下来进行判断和格式化。