【问题标题】:Not accessing the date picker gives the conversion error不访问日期选择器会导致转换错误
【发布时间】:2014-06-19 17:36:41
【问题描述】:

我在使用日期选择器的 Spring MVC 中的 .jsp 代码遇到问题。当我访问日期时间选择器时,代码工作正常。但是如果我尝试将该字段留空,即不使用日期选择器,它将 null 作为默认值(它应该),然后给出错误:

无法将 java.lang.String 类型的属性值转换为属性 ticComDropoofDate 所需的 java.util.Date 类型;嵌套异常是 org.springframework.core.convert.ConversionFailedException: Unable to convert value "" from type java.lang.String to type java.util.Date;嵌套异常是 java.lang.IllegalArgumentException

我附上我的代码,任何帮助将不胜感激。

我的控制器:

public class TicketController extends MasterController{

    @InitBinder
    protected void initBinder(WebDataBinder binder){
        if(binder.getTarget() instanceof TicketDetailsBean)
            binder.setValidator(new TicketDetailsValidator());
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
    }

       @RequestMapping(value="/TicketRegistration", method=RequestMethod.POST)
    public ModelAndView createTicketRegistration(@Valid TicketDetailsBean ticket, BindingResult result, Model model) throws SQLException{
        TicketManager dm = new TicketManager();
        TechManager dm1  = new TechManager();
        SimpleMailManager sm = new SimpleMailManager();
        ModelAndView modelAndView = new ModelAndView();
        if(!result.hasErrors()){
            try{
                String message = dm.saveTicketRegistration(ticket);
                /*if(check)
                {
                    TicketDetailsBean ticket1 = new TicketDetailsBean();
                    OwnerDetailsBean owner1 = new OwnerDetailsBean();
                    ticket1 = sm.fetchData(ticket);
                    owner1 = sm.fetchOwner(ticket1);

                }*/
                sm.sendMail();/*(owner1,ticket1);*/
                List<TicketDetailsBean> ticket2 = dm.findRegisteredTicket();
                if(message != null){
                     message = "Duplicate entry not allowed. Data with same name already in the database...";
                     modelAndView.addObject("Message", message);
                }
                modelAndView.setViewName("TicketDatabase");
                modelAndView.addObject("ticketDetailsBean", new TicketDetailsBean());
                modelAndView.addObject("ticketList", ticket2);
                modelAndView.addObject("techDetailsBean", new TechDetailsBean());
                modelAndView.addObject("tech", globalBean);
                return modelAndView;
            }catch (Exception e) {  
                e.printStackTrace();
            }
        }
        else{
            List<TechDetailsBean> tech = dm1.findRegisteredTech();
            modelAndView.addObject(result.getAllErrors());
            modelAndView.setViewName("TicketRegistration");
            modelAndView.addObject("ticketDetailsBean", new TicketDetailsBean());
            modelAndView.addObject("techDetailsBean", new TechDetailsBean());
            modelAndView.addObject("tech", globalBean);
            modelAndView.addObject("techList",tech);
            return modelAndView;
        }
        /*List<TicketDetailsBean> ticket2 = dm.findRegisteredTicket();
        modelAndView.addObject("ticketDetailsBean", new TicketDetailsBean());
        modelAndView.addObject("ticketList", ticket2);*/
        return modelAndView;
    }

我的jsp:

<script>     
        $(function() {
                    $( "#datepicker" ).datepicker({ 
                              dateFormat: 'yy-mm-dd',
                            showOn: "button",
                          buttonImage: "<%=request.getContextPath() %>/resources/images/calendar.gif",
                          buttonImageOnly: true 
                       });
              }).val('');
              $(function() {
                    $( "#datepicker1" ).datepicker({ dateFormat: 'yy-mm-dd',
                        showOn: "button",
                          buttonImage: "<%=request.getContextPath() %>/resources/images/calendar.gif",
                          buttonImageOnly: true 
                });
             }).val('');
     </script>  

     <form:form modelAttribute="ticketDetailsBean" action="TicketRegistration" method="post">

<table>
    <tr>
        <td>
            <h1>Ticket Registration Form</h1>
            <h3>Please enter the information below</h3>
            <h3>click "<b>Save</b>" when complete. </h3>
            <h3> Fields marked with an asterisk '<b>*</b>' are required.</h3>
            <h3> Click "<b>Reset</b>" to clear the fields</h3>
        </td>
    </tr>

    <tr>
        <td>
            <fieldset title="info">
                <legend><b>Ticket Information</b></legend>
                <table>
                    <tr>
                        <td align="left"><form:label for="ticDate" path="ticDate" cssErrorClass="error">* Ticket Date :</form:label></td>
                        <td align="left"><form:input path="ticDate" id="datepicker1" size="35" maxlength="35"/> <form:errors path="ticDate" /></td> 
                    </tr>
                    <tr>
                        <td align="left"><form:label for="ticServicetag" path="ticServicetag" cssErrorClass="error">* Service Tag Number :</form:label></td>
                        <td align="left"><form:input name="ticServicetag" path="ticServicetag" id="ticSrvctag" size="35" maxlength="35" value = "${computerList.comServicetag}" /> <form:errors path="ticServicetag" /></td>    
                    </tr>
                    <tr>
                        <td align="left"><form:label for="ticOwnerSuUsername" path="ticOwnerSuUsername"  cssErrorClass="error">* Owner Su_username :</form:label></td>
                        <td align="left"><form:input path="ticOwnerSuUsername" id="owsusenm" size="35" maxlength="35" value ="${computerList.comOwnerSUUsername }" /> <form:errors path="ticOwnerSuUsername" /></td>    
                    </tr>
                    <tr>
                        <td align="left"><form:label for="ticTechname" path="ticTechname" cssErrorClass="error">* Tech Name :</form:label></td>
                        <td align="left"> 
                            <select name="ticTechname" id = "ticTechname" id="slectboxid1">
                                 <option value = ""> ---Select---             </option>
                                 <c:forEach var="item" items="${techList}">
                                      <option value = "${item.techName}"><c:out value= "${item.techName}"/></option>
                                  </c:forEach>
                            </select>
                        <form:errors path="ticTechname" /></td>
                    </tr>
                    <tr>
                        <td align="left"><form:label for="ticComProblem" path="ticComProblem" cssErrorClass="error">* Problem :</form:label></td>
                        <td align="left"><form:textarea path="ticComProblem" rows ="3" cols ="27"/> <form:errors path="ticComProblem" cssErrorClass="error" /></td> 
                    </tr>
                    <tr>
                        <td align="left"><form:label for="ticComments" path="ticComments" cssErrorClass="error">  Comments :</form:label></td>
                        <td align="left"><form:textarea path="ticComments" rows = "3" cols = "27"/> <form:errors path="ticComments" /></td> 
                    </tr>
                    <tr>
                        <td align="left"><form:label for="ticItemtoOrder" path="ticItemtoOrder" cssErrorClass="error">  Item To Order :</form:label></td>
                        <td align="left"><form:input path="ticItemtoOrder" size="35" maxlength="35" /> <form:errors path="ticItemtoOrder" /></td>   
                    </tr>
                    <tr>
                        <td align="left"><form:label for="ticComDropoofDate" path="ticComDropoofDate" cssErrorClass="error">  Computer Drop Off Date:</form:label></td>
                        <td align="left"><form:input path="ticComDropoofDate" id="datepicker" size="35" maxlength="35" /> <form:errors path="ticComDropoofDate"/></td>  
                    </tr>
                    <tr>
                        <td align="left"><form:label for="ticAssignedTech" path="ticAssignedTech" cssErrorClass="error">* Tech Assigned :</form:label></td>
                         <td align="left"> 
                            <select name="ticAssignedTech" id = "ticAssignedTech" id="slectboxid2">
                                 <option value = ""> ---Select---         </option>
                                 <c:forEach var="item" items="${techList}">
                                      <option value = "${item.techName}"><c:out value= "${item.techName}"/></option>
                                  </c:forEach>
                            </select>
                            <form:errors path="ticAssignedTech" />
                        </td>
                    </tr>
                    <tr>
                        <td align="left"><form:label for="ticStatus" path="ticStatus" cssErrorClass="error">* Ticket Status :</form:label></td>
                        <td align="left">
                            <select name="ticStatus" id = "ticStatus" id="slectboxid3">
                            <option value="">---Select---               </option>
                            <option value="Open">  Open  </option>
                            <option value="InProgress">In Progress</option>
                            <option value="Closed">Closed</option>
                            </select>
                            <form:errors path="ticStatus" />
                        </td>   
                    </tr>
                    <tr>
                        <td align="left"><form:label for="ticAddEquipments" path="ticAddEquipments" cssErrorClass="error">  Additional Equipments dropped with Computer :</form:label></td>
                        <td align="left"><form:textarea rows= "3" path="ticAddEquipments" cols ="27"/> <form:errors path="ticAddEquipments" /></td> 
                    </tr>           
            </table>
            </fieldset>
            <fieldset>
                <div align="center">
                <form action="TicketDatabase" method="get">
                    <input type="submit" name="submit" value="Save"/>
                    <input type="reset" name="reset"/>
                </form>
                </div>
            </fieldset>
    </td>
    </tr>
    </table>

【问题讨论】:

    标签: java spring jsp spring-mvc


    【解决方案1】:

    异常信息:

    Unable to convert value "" from type java.lang.String to type java.util.Date

    spring throws 因为你没有通知 spring 将空字符串转换为 null。

    binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
    

    如果你想在空字符串时为空,请传递true

    binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    


    Spring CustomDateEditor 构造函数 java docs 具有:

    public CustomDateEditor(DateFormat dateFormat, boolean allowEmpty)

    创建一个新的CustomDateEditor 实例,使用给定的DateFormat 进行解析渲染allowEmpty 参数说明是否应该使用空字符串 允许解析,即被解释为空值。否则, 在这种情况下会抛出 IllegalArgumentException。

    参数

    dateFormat - DateFormat 用于解析和渲染

    allowEmpty - 如果应该允许空字符串

    【讨论】:

    • 我试过了,但它似乎仍然不起作用。我试过 Java.sql.date 也是同样的问题。
    • @Bubble 不客气,如果它解决了您的问题,您可以将此标记为答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-26
    • 1970-01-01
    相关资源
    最近更新 更多