【问题标题】:Spring - Thymeleaf Date typeSpring - Thymeleaf 日期类型
【发布时间】:2015-04-09 23:50:30
【问题描述】:

我是 Spring 和 thymeleaf 的新手,很抱歉这个愚蠢的问题。

我有一个表单,它必须根据用户选择的日期过滤一些数据。 我有这门课:

public class RequestFilterEntity {
  private Date requestedAt;
  private Date dateScheduled;
  ...
 }

我在控制器中有这个端点:

 @RequestMapping(value = "/requests", method = POST)
    public String filterRequests(RequestFilterEntity requestFilter, Model model) {

    model.addAttribute("requestFilter", new RequestFilterEntity());

    return "admin/reporting/filter_requests";
}

这个视图:

 <form method = "post" th:object="${requestFilter}" th:action="@{|/admin/reporting/requests|}">

    <div class="form-group">
      <label for="requested">Requested at </label>
      <input id="requested" type="date" class="form-control" th:field="*{requestedAt}"/>
    </div>

我希望控制器传递给视图的对象 requestFilter 将 Date requestedAt 设置为用户选择的日期(请注意,我使用的是 input type="date")

这有意义吗?我的视图有错误。有人可以帮我吗?我的错在哪里?

【问题讨论】:

  • 能否请您提供您遇到的错误?
  • 错误是 HTTP 状态 400“客户端发送的请求在语法上不正确”。观点有些问题。我什至不知道如何调试它。我确定问题出在日期类型上,因为如果我摆脱它,视图就会正常加载
  • 大部分浏览器不支持type=date

标签: spring date thymeleaf


【解决方案1】:

问题很少。

  1. 您正在从控制器传递一个空对象并期望它显示在您的视图中。

model.addAttribute("requestFilter", new RequestFilterEntity());

  1. 您没有格式化您的日期对象。请将此initbinder 添加到您的控制器

InitBinder 用于自定义日期编辑器

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

【讨论】:

  • 我传递了一个空对象,因为我希望 View 设置我的对象变量(它适用于其他 int 和 String 变量,但不适用于日期类型)
  • 我没听懂你。你能进一步解释一下这条评论吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-13
  • 2018-09-04
  • 2021-06-26
  • 2020-07-08
  • 2018-10-27
相关资源
最近更新 更多