Java 输入类型=“日期”百里香叶

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38693971/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 20:31:20  来源:igfitidea点击:

Input type="date" thymeleaf

javahibernatedateinputthymeleaf

提问by zzheads

I need to add date to my entity and let the user set it in web form. This field needs to have today's date filled in by default.

我需要将日期添加到我的实体并让用户在 Web 表单中设置它。默认情况下,此字段需要填写今天的日期。

1. <input type="date" value="2016-08-01"> 

shows correct date setted for default

显示为默认设置的正确日期

2. <input type="date" th:value="${startDate}"> 

shows date picker without any value (note: String startDate = "2016-08-01";)

显示没有任何值的日期选择器(注意:String startDate = "2016-08-01";)

3. <input type="date" th:field="${startDate}"> 

generates 400 error (Bad request) (note: Date startDate = new Date();)

生成 400 错误(错误请求)(注意:Date startDate = new Date();)

So, question is: how to use thymeleaf for input date?

所以,问题是:如何使用百里香叶作为输入日期?

  • can I use Date() datatype for input and store such data?
  • how I need to set "th:field" in form?
  • how I need to set "th:value" in same form?
  • 我可以使用 Date() 数据类型输入并存储此类数据吗?
  • 我需要如何在表单中设置“th:field”?
  • 我需要如何以相同的形式设置“th:value”?

My controller(s):

我的控制器:

@RequestMapping("/project_new")
public String createProject(Model model) {
    Project project = new Project ();
    List<Role> roles = mRoleService.findAll();

    project.setStart(new Date());

    model.addAttribute("page_title", "create project");
    model.addAttribute("roles", roles);
    model.addAttribute("statuses", Status.values());
    model.addAttribute("project", project);
    return "project_new";
}

@RequestMapping(value = "/project_new", method = RequestMethod.POST)
public String createProject(@ModelAttribute Project project, Model model) {
    // Fill id field for project.rolesNeeded
    mRoleService.setRolesId(project.getRolesNeeded());
    project.fixCollaboratorsAndRoles();

    mProjectService.save(project);
    return "redirect:/";
}

My template:

我的模板:

<form th:action="@{/project_new}" method="post" th:object="${project}">
  <div class="project-list single">
    <label for="name">Name:</label>
    <input type="text" id="name" required="true" th:placeholder="*{name}" th:value="*{name}" th:field="*{name}"/>
    <label for="description">Description:</label>
    <textarea rows="5" id="description" type="text"  required="true" th:placeholder="*{description}" th:value="*{description}" th:field="*{description}"/>

    <label for="date-started">Date started:</label>
    <input type="date" th:value="${project.start}" th:field="${project.start}" id="date-started"/>

    <div>
      <label for="project_status">Project Status:</label>
      <div class="custom-select">
        <span class="dropdown-arrow"></span>
        <select th:field="*{status}" id="project_status">
          <option th:each="s : ${statuses}" th:value="${s}" th:text="${s}">Active</option>
        </select>
      </div>
    </div>

  <div class="roles-collaborators">
    <ul class="checkbox-list">
      <li th:if="${role.name} ne 'Undefined'" th:each="role : ${roles}">
      <input type="checkbox"  th:value="${role}" th:field="${project.rolesNeeded}" class="checkbox"/>
      <span th:text="${role.name}" th:value="${role}" class="checkbox">Developer</span>
      </li>
    </ul>
  </div>

  <div class="actions">
    <button type="submit" class="button">Save</button>
    <a th:href="@{/}" class="button button-secondary">Cancel</a>
  </div>
</div>
</form>

Project entity:

项目实体:

@Entity
public class Project {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@NotNull
@Size (min = 3)
private String name;

@Column(columnDefinition="TEXT")
private String description;

@Column
private Status status;

@Column
private Date start;

@ManyToMany
@LazyCollection(LazyCollectionOption.FALSE)
private List<Role> rolesNeeded;

@ManyToMany
@LazyCollection(LazyCollectionOption.FALSE)
private List<Collaborator> collaborators;

public Date getStart() {
    return start;
}

public void setStart(Date start) {
    this.start = start;
}

采纳答案by BitExodus

Taking a look at the comment with the error log it seems to be a conversion problem between Stringto java.util.Date. After searching for a while in the Thymeleaf GitHub I saw two issues which can explain how to proceed in this case:

纵观在与错误日志的评论似乎是之间的转换问题Stringjava.util.Date。在 Thymeleaf GitHub 中搜索了一段时间后,我看到两个问题可以解释在这种情况下如何进行:

  • Discussion of the conversion including date in this issue.
  • Implementation of the conversion is explained here.
  • 本期讨论的转换包括日期。
  • 此处解释了转换的实现。

From the last point, I added an annotation to the start date of your project class:

从最后一点,我在你的项目类的开始日期添加了一个注释:

// This is "org.springframework.format.annotation.DateTimeFormat"
@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date start;

And after that, I was able to receive the date in your controller POST method.

之后,我能够在您的控制器 POST 方法中接收日期。

Take into account you also need to change your th:valueand th:fieldattributes from your template for the date value from ${project.start}to *{start}, as I wrote in the comments, as you did for the nameand descriptionfields.

考虑到您还需要将您的th:valueandth:field属性从模板中更改为日期值从${project.start}to *{start},正如我在评论中所写的那样,就像您对namedescription字段所做的那样。

回答by jais

Use string instead of Date

使用字符串代替日期

@DateTimeFormat(pattern = "yyyy-MM-dd")<br>
private String fromDate;