不访问日期选择器会产生转换错误

时间:2014-05-02 23:03:51

标签: java spring jsp spring-mvc

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

无法将类型为java.lang.String的属性值转换为属性ticComDropoofDate所需的类型java.util.Date;嵌套异常是org.springframework.core.convert.ConversionFailedException:无法将值类型“”从类型java.lang.String转换为类型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>

1 个答案:

答案 0 :(得分:0)

异常消息:

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));

如果你想在空字符串中使用null,则传递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 - 如果允许空字符串