日期在jsp的type表示_JSP表单日期输入字段

I've created a basic input form with a number of strings using Spring Web application in Intellij. The form successfully saves to the backend when using strings only so I decided to add a date field in the model and tried to modify to controller/jsp to accept this in the input form (and display in the record list). I'm having problems with the input form not getting the value.

Entity:

@Temporal(TemporalType.DATE)

@DateTimeFormat(pattern="dd.MM.yyyy")

private Date dueDate;

public Date getDueDate() {

return dueDate;

}

public void setDueDate(Date dueDate) {

this.dueDate = dueDate;

}

JSP (I assume value should be blank here as I am starting with an empty field to fill in?):

Due Date:

"/>

Controller:

@RequestMapping(value = "/todos/add", method = RequestMethod.POST)

public String addUser(@ModelAttribute("todo") Todo todo, BindingResult result) {

System.err.println("Title:"+todo.getTitle());

System.err.println("Due Date:"+todo.getDueDate());

todoRepository.save(todo);

return "redirect:/todos/";

}

My debug shows Due Date:null so nothing is being send for my date field from the form when posted. This means that the date field is never saved then the repository save occurs.

解决方案

You have to register an InitBinder in your controller to let spring convert your date string to java.util.Date object and set it in command object. Include following in your controller :

@InitBinder

public void initBinder(WebDataBinder binder) {

SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy");

sdf.setLenient(true);

binder.registerCustomEditor(Date.class, new CustomDateEditor(sdf, true));

}

Modify your jsp with :

"/>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值