idea页面传值到controller 参数为User类型 通过转换器转换日期格式

日期转换编辑器

  • 页面通过form表单传值
    • 页面标签
    • 实体类 私有属性上添加注解
    • controller代码
    • 创建帮助类 baseController
    • config包下创建日期转换编译器类
    • 转换成功 查看输出信息

报错信息

Field error in object 'user' on field 'birthday': rejected value [2019-04-29]; codes [typeMismatch.user.birthday,typeMismatch.birthday,typeMismatch.java.util.Date,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [user.birthday,birthday]; arguments []; default message [birthday]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'birthday'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [@com.fasterxml.jackson.annotation.JsonFormat java.util.Date] for value '2019-04-29'; nested exception is java.lang.IllegalArgumentException]]

页面通过form表单传值

页面标签

<input type="text" placeholder="出生日期" onfocus="WdatePicker({dateFmt:'yyyy-MM-dd'})" name="birthday"/>

实体类 私有属性上添加注解

    @JsonFormat(shape = JsonFormat.Shape.STRING,pattern = "yyyy-MM-dd", timezone="GMT+8")
    private Date birthday;

controller代码

 /*完善用户信息*/
@RequestMapping("/user")
public String user(User user, HttpSession session){
     
        String name=user.getName();
        String sex=user.getSex();
        String address=user.getAddress();
        Date birthday=user.getBirthday();
        System.out.println(birthday);
        String nation=user.getNation();
        return "table";
    }

创建帮助类 baseController

public class baseController {
     
    @InitBinder
    public void initBinder(WebDataBinder binder) {
     
        SimpleDateFormat datetimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        datetimeFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new MyCustomDateEditor(datetimeFormat, true));
    }
}

config包下创建日期转换编译器类

/**
 * @ClassName: MyCustomDateEditor 
 * @Description: 自定义Date类型参数处理器 
 * @author L-liang
 * @date 2015年10月9日 下午3:56:19 
 *  
 */
public class MyCustomDateEditor extends PropertyEditorSupport{
     
	Logger logger = LoggerFactory.getLogger(MyCustomDateEditor.class);
	
	private final DateFormat dateFormat;
	private final boolean allowEmpty;
	private final int exactDateLength;
	/**
	 * Create a new CustomDateEditor instance, using the given DateFormat
	 * for parsing and rendering.
	 * 

The "allowEmpty" parameter states if an empty String should * be allowed for parsing, i.e. get interpreted as null value. * Otherwise, an IllegalArgumentException gets thrown in that case. * @param dateFormat DateFormat to use for parsing and rendering * @param allowEmpty if empty strings should be allowed */ public MyCustomDateEditor(DateFormat dateFormat, boolean allowEmpty) { this.dateFormat = dateFormat; this.allowEmpty = allowEmpty; this.exactDateLength = -1; } /** * Create a new CustomDateEditor instance, using the given DateFormat * for parsing and rendering. *

The "allowEmpty" parameter states if an empty String should * be allowed for parsing, i.e. get interpreted as null value. * Otherwise, an IllegalArgumentException gets thrown in that case. *

The "exactDateLength" parameter states that IllegalArgumentException gets * thrown if the String does not exactly match the length specified. This is useful * because SimpleDateFormat does not enforce strict parsing of the year part, * not even with {@code setLenient(false)}. Without an "exactDateLength" * specified, the "01/01/05" would get parsed to "01/01/0005". However, even * with an "exactDateLength" specified, prepended zeros in the day or month * part may still allow for a shorter year part, so consider this as just * one more assertion that gets you closer to the intended date format. * @param dateFormat DateFormat to use for parsing and rendering * @param allowEmpty if empty strings should be allowed * @param exactDateLength the exact expected length of the date String */ public MyCustomDateEditor(DateFormat dateFormat, boolean allowEmpty, int exactDateLength) { this.dateFormat = dateFormat; this.allowEmpty = allowEmpty; this.exactDateLength = exactDateLength; } /** * Parse the Date from the given text, using the specified DateFormat. */ @Override public void setAsText(String text) throws IllegalArgumentException { if (this.allowEmpty && !StringUtils.hasText(text)) { // Treat empty String as null value. setValue(null); } else if (text != null && this.exactDateLength >= 0 && text.length() != this.exactDateLength) { throw new IllegalArgumentException( "Could not parse date: it is not exactly" + this.exactDateLength + "characters long"); } else { try { setValue(this.dateFormat.parse(text)); } catch (ParseException e) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm"); try { setValue(sdf.parse(text)); } catch (Exception ex) { //如果yyyy-MM-dd HH:mm:ss 不能解析 传入的字符串, 换年月日的解析方式 SimpleDateFormat sdfx = new SimpleDateFormat("yyyy-MM-dd"); try { setValue(sdfx.parse(text)); } catch (ParseException exx) { logger.error("日期不能解析 text:"+text, e); throw new IllegalArgumentException("Could not parse date: " + exx.getMessage(), exx); } } } } } /** * Format the Date as String, using the specified DateFormat. */ @Override public String getAsText() { Date value = (Date) getValue(); return (value != null ? this.dateFormat.format(value) : ""); } }

转换成功 查看输出信息

在这里插入图片描述

你可能感兴趣的:(idea日期转换,String,转换为,Date)