通过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类型的参数全部拦截下来进行判断和格式化。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值