SpringMVC中的日期绑定以yyyy-MM-dd格式进行。

4
<tr class="rowsAdded">
        <td><input name="item" class="form-control" type="text" placeholder="Item" /></td>
        <td><input name="amount" class="form-control" type="number" placeholder="Amount" /></td>
        <td><input name="expenseDate" class="form-control" type="date"placeholder="ExpenseDate" /></td>
</tr>

以下是我的控制器和初始化绑定器:
@RequestMapping (value = "/saveExpenses", method=RequestMethod.POST)
    public String saveExpenses (@RequestBody ExpenseDetailsListVO expenseDetailsListVO, Model model,BindingResult result) {
        if (result.hasErrors()) {
            System.out.println(result.getFieldError().getField().toString()+" error");
        }
        System.out.println(expenseDetailsListVO);       
        return "success";
    }

@InitBinder
    public void initBinder(WebDataBinder webDataBinder) {
     SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
     dateFormat.setLenient(false);
     webDataBinder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
     }

这种方式我想要的日期格式不起作用,这是我得到的输出结果: expenseDate=Wed Mar 18 05:30:00 IST 2015 但我想要它按照特定的格式如yyyy-MM-dd来显示...请建议一种方法。


1
我猜你的ExpenseDetailsListVO类有一个Date类型的成员。当你在expenseDetailsListVO上调用println时,它只会调用该Date成员的toString()方法。你的绑定器没有任何作用。因此,你得到了Date的默认字符串表示形式。你可以改变打印对象的方式,或者使用一个新的类来扩展Date,但是它有一个不同的toString()方法来存储你的费用日期。 - fsaftoiu
是的,你说得对...成员是日期类型,因为在后端它也是日期类型,所以在从VO转换为DO时会很容易...那么现在我该怎么办? - Sharique
@Sharique 尝试使用 dateFormat.format(yourDateObj) - Abhishek Nayak
3个回答

10

这样不是更容易吗?

实体或表单后备对象:

class Foo {

  /* handles data-binding (parsing) and display if spring form tld or spring:eval */
  @DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
  private Date expenseDate;

  ...
}

在一个表单中:

<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>

<form:form modelAttribute="modelAttributeName">
  <form:input type="date" path="expenseDate" />
</form:form>

或者只是用于展示:

<%@ taglib uri="http://www.springframework.org/tags" prefix="spring" %>

<spring:eval expression="modelAttributeName.expenseDate" />

一些吹毛求疵的注意事项:

  1. 使用CSS进行布局,不要使用表格。可以参考Bootstrap的网格系统。
  2. 对于表单,请使用Post-Redirect-Get模式。
  3. 使用Spring的Form taglib进行适当的HTML转义和CSRF防护。
  4. 在控制器处理程序方法中使用@Validated进行验证。
  5. 您的表单中“placeholder”前面缺少一个空格。

有关最佳实践,请参见我的帖子:Spring MVC:验证、Post-Redirect-Get、部分更新、乐观并发性、字段安全


8

我不知道这个答案是否能帮到你?我的一个Entity类如下所示...

@Entity
@Table(name = "TAIMS_INC_INCIDENT")
public class Incident implements Serializable{

    @DateTimeFormat(pattern = "dd/MM/yyyy") // This is for bind Date with @ModelAttribute
    @Temporal(TemporalType.DATE)
    @Column(name = "inc_date")
    private Date incidentDate;

}

这是输入的方式: GUI
<input type="text" id="incident-date" name="incidentDate" value="23/08/2017" />

这里是Spring控制器方法..


    @RequestMapping(value = "/saveIncident.ibbl", method = RequestMethod.POST)
    public ModelAndView saveIncident(
                @ModelAttribute("incident")
                Incident incident,
                BindingResult result){

                System.out.println(incident.getIncidentDate());
                // Wed Aug 23 00:00:00 BDT 2017

    }

这个工作正常。 Incident incident 包含 incidentDate = Wed Aug 23 00:00:00 BDT 2017。

如果您不想在实体类中使用 @DateTimeFormat(pattern = "dd/MM/yyyy"),那么请将下面的方法放入控制器类中...

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }

0
我想说的是,您的绑定器可能运行良好。它所做的是从HTTP请求正文中获取格式为yyyy-MM-dd的字符串并将其转换为日期对象。但这就是它所做的全部。之后您可以自行处理该日期对象。如果要将其作为字符串传递给程序的其他部分,则应进行转换,可以使用SimpleDateFormatter进行转换。

嘿,感谢你的建议! HTTP请求正文绑定在yyyy-MM-dd格式中,但是我能否在绑定之前更改其格式,例如使用dd-MM-yyyy格式? - Sharique
你可以将其类型保留为String,然后在绑定器中首先将其转换为Date,然后再转换回实际想要的String格式。我应该说这似乎相当奇怪,但由于您没有提供有关您想要使用该日期的任何信息,因此我无法提出其他建议。 - fsaftoiu
我只是在寻求知识...我只想将它转换为日期对象,然后保存到数据库中... 那么我应该在哪里将其转换为对象..我的意思是如何实现? - Sharique
它已经是一个对象了,确切的类是Date。只需将其传递给您的数据库保存方法,应该就可以了。 - fsaftoiu
但它是字符串类型,我的后端POJO类是日期类型...假设我也将其转换为日期类型,但是在我的数据库中它仍然是日期类型。 - Sharique
这是如何工作的:1-请求进来;2-Spring MVC调用您的绑定器并将expenseDate转换为Date;3-Spring MVC调用您的saveExpenses方法。此时,您的expenseDetailsListVO的expenseDate成员中的日期已经是Date类型。 - fsaftoiu

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接