JSP表单日期输入字段 [英] JSP form date input field

查看:1241
本文介绍了JSP表单日期输入字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Intellij中的Spring Web应用程序创建了一个包含许多字符串的基本输入表单。当只使用字符串时,表单成功保存到后端,所以我决定在模型中添加一个日期字段,并尝试修改为controller / 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.

实体:

@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(我假设值应为空白,因为我从空开始要填写的字段?):

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

    <div class="control-group">
        <form:label cssClass="control-label" path="dueDate">Due Date:</form:label>
        <div class="controls">
            <input type="text" path="dueDate" class= "date" name = "dueDate" value = "<fmt:formatDate value="" pattern="MM-dd-yyyy" />"/>
        </div>
    </div>

控制器:

@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/";
}

我的调试显示截止日期:null因此我的日期字段没有发送任何内容从发布时的表格。这意味着永远不会保存日期字段,然后发生存储库保存。

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.

推荐答案

您必须在控制器中注册一个InitBinder让spring将您的日期字符串转换为java.util.Date对象,并将其设置在命令对象中。在控制器中包含以下内容:

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));
    }

用以下内容修改你的jsp:

Modify your jsp with :

<input type="text" path="dueDate" class= "date" name = "dueDate" value = "<fmt:formatDate value="${cForm.dueDate}" pattern="MM-dd-yyyy" />"/>

这篇关于JSP表单日期输入字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆