java - 在 Spring mvc 中设置日期和时间

标签 java mysql spring hibernate jsp

我正在使用最新的 spring 和 hibernate。我需要从jsp页面获取日期和时间并希望插入到mysql数据库中。我使用 TIMESTAMP 作为一个字段的数据类型。当我尝试保存时,没有错误,但显示“HTTP 状态 [400] – [错误请求]”。

最后我发现,日期和时间格式有问题(可能是注释或MySQL数据类型或jsp页面)。因为我尝试在不更改日期时间值 (path="startDateTime") 的情况下更新表单。已成功更新。当我尝试更改日期时间中的值(path="startDateTime")时,它显示“HTTP 状态 [400] – [错误请求]”。 p>

我需要将日期和时间更新到数据库。我尝试了很多方法,但都失败了。

模型类

public class Survey{

//other declaration

    @Column(name="startDateTime",columnDefinition="TIMESTAMP")      
    @Temporal(TemporalType.TIMESTAMP)
    @DateTimeFormat(pattern="yyyy-MM-dd'T'HH:mm:ss")
    private Date startDateTime;
}

jsp页面

<spring:url value="/survey/save" var="saveURL"></spring:url>
<form:form action="${saveURL}" method="POST" modelAttribute="surveyForm">
//other stuffs
<form:input type="datetime-local" path="startDateTime" />
</form:form>

Controller

public ModelAndView saveSurvey(@ModelAttribute("surveyForm") Survey survey) {       
    surveyService.saveOrUpdate(survey);
    return new ModelAndView("redirect:/survey/list");
}

最佳答案

为了采用良好的实践,我建议使用 JAVA 8 LocalDateTime 类。 所以像这样修改你的模型类

public class Survey{

//other declaration

    @Column(name="startDateTime",columnDefinition="TIMESTAMP")      
    private LocalDateTime startDateTime;
}

使用JAVA 8 LocalDateTime类时,不再需要添加@Temporal(TemporalType.TIMESTAMP)

之后,您需要通过实现这样的 Converter 接口(interface)来创建 LocalDateTimeConverter 类

import org.springframework.core.convert.converter.Converter;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public final class LocalDateTimeConverter implements Converter<String, LocalDateTime> {

    private final DateTimeFormatter formatter;

    public LocalDateTimeConverter(String dateFormat) {
        this.formatter = DateTimeFormatter.ofPattern(dateFormat);
    }

    @Override
    public LocalDateTime convert(String source) {
        if (source == null || source.isEmpty()) {
            return null;
        }

        return LocalDateTime.parse(source, formatter);
    }
}

然后在您的配置类中注册 LocalDateTimeConverter 类,如下所示

import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
@EnableWebMvc
class WebMvcContext extends WebMvcConfigurerAdapter {

    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverter(new LocalDateTimeConverter("yyyy-MM-dd'T'HH:mm:ss.SSS"));
    }
}

以上就是全部内容,希望能解决您的问题。 您可以了解更多here

好吧,我仍然想建议,为什么不让 hibernate 通过使用 @CreationTimestamp 来为您完成日期时间更新的责任,而不是将责任留给您的站点用户?和@UpdateTimestamp hibernate 的注释或最好使用 JPA @PrePersist@PreUpdate像这样的注释

@Column(name="startDateTime")      
@PrePersist
private LocalDateTime startDateTime;

@Column(name="updatedDateTime")      
@PreUpdate
private LocalDateTime updatedDateTime;

通过这种方法,您不再需要在表单中添加 startDateTime 字段,因为 hibernate 会自动为您插入和更新这些列。

注意:并非所有浏览器都支持表单输入类型 datetime-local。

关于java - 在 Spring mvc 中设置日期和时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44819472/

相关文章:

spring for mongodb转义参数以避免SQL注入(inject)

java - Spring JDBC在运行SQL脚本时无法处理DECLARE语句

java - spring-Unnamed bean 定义既不指定 'class' 也不指定 'parent' 也不指定 'factory-bean' - 无法生成 bean 名称

java - mAdapter.notifyDataSetChanged() 在某些情况下不起作用

php - 使用 PHP 将 mySQL 转换为 XLS?

MySQL - 带日期时间的复合唯一键

java - 触发 Hibernate 和 Java App

java - JTextArea 始终为空?

java - 在 JSP 页面中使用 JSON 数组进行响应

java - JavaFX 中以编程方式生成的 TriangleMesh 的纹理坐标