向数据库添加日期时出错

时间:2014-11-01 19:04:33

标签: spring-mvc

通过Hibernate将日期从jsp添加到数据库时,我收到了错误。 如果有人知道解决方案,请告诉我。 感谢您的帮助。下面是我的代码片段。

register.jsp

<form:input path="date" id="datepicker"/>

Registration.java

import java.sql.Timestamp;
public class Registration {
private Timestamp date;
    public Timestamp getDate() {
        return date;
    }
    public void setDate(Timestamp date) {
        this.date = date;
    }
}

HelloController.java

@Controller
@RequestMapping("/library/*")
public class HelloController {
    @RequestMapping(value="success", method = RequestMethod.POST)
    public String addUser(@ModelAttribute("register") Registration register, ModelMap model) {
        System.out.println(register.getFirstName());
        registerService.addUsers(register);
        return "register";
    }
}

从jsp添加日期到数据库我得到了以下错误

org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors
Field error in object 'register' on field 'date': rejected value [25/11/2014]; codes [typeMismatch.register.date,typeMismatch.date,typeMismatch.java.sql.Timestamp,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [register.date,date]; arguments []; default message [date]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.sql.Timestamp' for property 'date'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [java.sql.Timestamp] for property 'date': no matching editors or conversion strategy found]
    at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.doBind(HandlerMethodInvoker.java:818)
    at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.resolveHandlerArguments(HandlerMethodInvoker.java:367)
    at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:171)
    at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:436)
    at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:424)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:923)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:789)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:643)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:723)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:861)
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:606)
    at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
    at java.lang.Thread.run(Thread.java:659)

2 个答案:

答案 0 :(得分:1)

如果您可以使用java.util.Date对象而不是TimeStamp对象。以下代码将解决您的问题,

在您的模型类中,Registration.java

import java.util.Date;
public class Registration {
private Date date;
    public Date getDate() {
        return date;
    }
    public void setDate(Date date) {
        this.date = date;
    }
}

在您的控制器类中,HelloController.java

@Controller
@RequestMapping("/library/*")
public class HelloController {

@Override
@InitBinder
public void initBinder(WebDataBinder binder) {

   SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
   dateFormat.setLenient(false);
   binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
}

@RequestMapping(value="success", method = RequestMethod.POST)
public String addUser(@ModelAttribute("register") Registration register, ModelMap model) {
    System.out.println(register.getFirstName());
    registerService.addUsers(register);
    return "register";
}
}

提交jsp表单后,默认情况下请求中的所有参数都是String类型。在Spring-MVC中,将所有String值转换为相应的类型并将其与Model类变量绑定是initBinder的职责。

答案 1 :(得分:0)

问题似乎是时间戳对象和从JSP接收的日期字符串之间的映射。

您可以通过以下任何方式解决此问题。

  1. 将Register类的日期变量类型更改为String类型,稍后在服务或DAO层中将其转换为TimeStamp对象,如下所示。

    日期日期=新日期(date_received_as_string);

    Timestamp timestamp = new Timestamp(date.getTime());

  2. 或者您可以编写JSON Serializer。首先使用JSONSerialize注释日期变量。

    @JsonSerialize(using = CustomSerializer.class)

    私人时间戳日期;

  3. 提供CustomSerializer类的实现后,如下所示。

    public class CustomSerializer extends JsonSerializer<Timestamp> {
        @Override
        public void serialize(Timestamp date, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
    
            //Now write you code for converting string to TimeStamp Object.
    
        }
    }
    

    同样,你也可以为TimeStamp Object编写JsonDeserializer。