通過InitBinder註解,做到全局的格式化轉換

首先自定義一個格式轉換類(我們以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類型的參數全部攔截下來進行判斷和格式化。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章