如何获得"日期和时间"从html表单输入并使用Spring Boot保存到MySQL数据库?

时间:2018-01-05 13:43:59

标签: java html mysql spring spring-boot

我想做什么: 用户将通过html表单输入日期和时间,这些值将保存到MySQL数据库中。

createPost.html

<form action="#" th:action="@{/createPost}" th:object="${post}" method="POST">      

        <p>Description: <input type="text" th:field="*{text}" /> </p>
        <!-- 
        <p>Time: <input type="datetime-local" th:field="*{dateTime}" /> </p>
         -->
        <p>date: <input type="date" th:field="*{date}" /></p>
        <p>time: <input type="time" th:field="*{time}" /></p>
        <p><input class="submitButton" type="submit" value="Submit" /> </p>


    </form>

Post.java

@Entity
public class Post { 

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long id;    
private String user;
private String text;
/*
@DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm")
private LocalDateTime dateTime;
*/


private java.sql.Date date;
private LocalTime time;

@Temporal(TemporalType.TIMESTAMP)
private java.util.Date myDate;  
//getters ans setters

}

PostController.java

@RequestMapping(value="/createPost", method=RequestMethod.POST)
public String createPost(@ModelAttribute Post post){
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    String currentUser = authentication.getName();
    post.setUser(currentUser);
    postRepository.save(post);
    return "redirect:/";
}

目前我收到此错误:

&#34;无效的属性&#39;日期&#39; bean类[com.example.demo.Post]:Bean属性&#39; date&#39;不可读或getter方法无效:getter的返回类型是否与setter的参数类型匹配?&#34;

我尝试过很多不同的东西,但我无法解决任何问题。 获取用户日期和时间并将其保存到数据库的推荐方法是什么?

修改

  

您只能绑定可以使用简单类型定义的模型对象。当对象从客户端序列化到服务器时,它不了解复杂类型(如java.time.LocalDate),除非它们表示为简单类型的内容。

我现在通过编写一个将字符串转换为sql.Date

的函数来解决这个问题
public Date getDateFromString(String dateString){
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    java.util.Date parsed = null;
    try {
        parsed = format.parse(dateString);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    Date date = new Date(parsed.getTime());
    return date;
}

并将PostController.java更改为:

@RequestMapping(value="/createPost", method=RequestMethod.POST)
public String createPost(@ModelAttribute Post post, String date){
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    String currentUser = authentication.getName();      
    post.setUser(currentUser);      

    Utilities utilities = new Utilities();              
    post.setDate(utilities.getDateFromString(post.getDatestring()));

    postRepository.save(post);
    return "redirect:/";
}

丑陋,但至少它有效,如果有人有更好的解决方案,请告诉

1 个答案:

答案 0 :(得分:1)

嗯,屏幕后面会发生的是,您的浏览器会将日期和时间都作为字符串发送,例如2018-01-0513:37。然后Spring必须将这些转换为java.sql.Datejava.time.LocalTime

正常情况下,Spring java.util.Date a formatterjava.sql.Datejava.sql.Date据我所知。但出于某种原因,如果我测试它,它似乎适用于java.time.LocalTime

尽管如此,Formatter还没有现有格式化程序,因此您必须编写自己的转换器。这可以通过实施@Component public class LocalTimeFormatter implements Formatter<LocalTime> { @Override public LocalTime parse(String s, Locale locale) throws ParseException { try { return LocalTime.parse(s, DateTimeFormatter.ofPattern("HH:mm", locale)); } catch (DateTimeParseException ex) { throw new ParseException(ex.getMessage(), ex.getErrorIndex()); } } @Override public String print(LocalTime localTime, Locale locale) { return localTime.format(DateTimeFormatter.ofPattern("HH:mm", locale)); } } 来完成,例如:

date

您获得的异常表示您在getter / setter类型中存在不匹配,因此我假设您使用与res.status(404).render('404template') 字段使用的类型不同的类型的某个地方存在冲突的getter / setter 。但是你展示的代码应该可以正常工作,所以我不知道它来自哪里。