spring mvc 绑定 date 类型 demo

其他技术

2018-01-03

220

0

技术:spring-5.0.0.RELEASE

运行环境:IDEA 15.2 + jdk8 + windows10 + spring-5.0.0.RELEASE

demo功能:提供一个spring mvc 绑定 date 类型数据的demo

继承PropertyEditorSupport,重写setAsText()

import java.beans.PropertyEditorSupport;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by francis on 2018/1/4.
 */
public class DateEditor extends PropertyEditorSupport {
    @Override
    public void setAsText(String text) throws IllegalArgumentException {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = null;
        try {
            date = format.parse(text);
        } catch (ParseException e) {
            format = new SimpleDateFormat("yyyy-MM-dd");
            try {
                date = format.parse(text);
            } catch (ParseException e1) {
                e1.printStackTrace();
            }
        }
        setValue(date);
    }
}

在父类controller中注册

import com.ctrip.datebinder.DateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RestController;

import java.lang.annotation.Annotation;
import java.util.Date;

/**
 * Created by francis on 2018/1/4.
 */
@RestController
public class BaseController implements Controller {
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(Date.class, new DateEditor());
    }

    @Override
    public String value() {
        return null;
    }

    @Override
    public Class<? extends Annotation> annotationType() {
        return null;
    }
}

所有继承这个父类controller的controller都能生效

@RestController
@RequestMapping("/")
public class IndexController extends BaseController {
    @RequestMapping("1")
    public String index(Date date) {
        System.out.println(date);
        return "hi";
    }
}

测试访问

http://localhost:8080/1?date=2017-02-12

输出 hi, 查看控制台输出 

欢迎添加微信,互相学习↑↑↑ -_-

发表评论

全部评论:0条

白老虎

programming is not only to solve problems, ways to think