Announcement Announcement Module
Collapse
No announcement yet.
Date problem on form Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Date problem on form

    Hi all,
    I have this problem that came up unexpected with a Date field on form and would appreciate any help on what is causing it and how to solve it.

    I would like to use date format dd.MM.yyyy.

    We'll take 15th December 2005 for example (but it isn't date specific) so expected result is: 15.12.2005.

    When I try to access value like this:

    Code:
    <spring:nestedPath path="command">
    <spring:bind path="activationDate">
    <tr>
      <td><fmt:message key="productDetails.form.activationDate"/></td>
      <td><c:out value="${status.value}"/></td>
    </tr>
    </spring:bind>
    </spring:nestedPath>
    the result is 15.00.2005, but when I do this

    Code:
    <c:out value="${command.activationDate}"/>
    the result is 2005-12-15

    I did add this in initBinder>

    Code:
    Locale locale = ExtendedControllerUtils.getCurrentLocale(p_request);
    String dateFormatString = getText("defaultDateFormat", locale);
    SimpleDateFormat dateFormat = new SimpleDateFormat(dateFormatString);
    dateFormat.setLenient(false);
    p_binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    the date format in locale is dd.mm.yyyy.
    I tried adding hardcoded date format like dd.MM.yyyy and then display is ok, but I get binding errors when submiting.

    Another thing is that I use the same controller class for two different forms and both have date fields. One works ok, the other has this problem.
    I ran out of ideas...

    hippo
    Last edited by Hippo; Jan 22nd, 2008, 03:37 AM.

  • #2
    There is a difference between 'mm' and 'MM' the first is for the minutes, the MM is for the months... So I actually find it weird that your default would be 'dd.mm.yyyy'... Clearly stated by the SimpleDateFormat javadocs

    dd.MM.yyyy is the correct one to use, this requires caution with input it always requires 2 digits for the day and month, so 1.1.2008 will fail. What is the bind exception you get?

    Comment


    • #3
      The problem occurs when displaying form view, so before any user input is done.
      Value for the date field comes from the database.

      Command class contains java.util.Date member that is set by setter method with the value provided from database. After setting the value is 2005-12-15.

      When date format is set to dd.MM.yyyy rendering form view results in
      Code:
      2008-01-22 10:47:56,091 ERROR [org.apache.catalina.core.ContainerBase.[Catalina].[localhost].[/popai].[jsp]] - <Servlet.service() for servlet jsp threw exception>
      javax.servlet.jsp.el.ELException: Attempt to convert String "15.11.2005" to type "java.util.Date", but there is no PropertyEditor for that type

      Comment


      • #4
        Are you sure your propertyeditor is registered for java.util.Date and not mistakenly java.sql.Date?! Next to that do you use a POST or a GET to submit your form, make sure your initBinder method is called.

        Comment


        • #5
          This is a relevant part of a logger output


          Code:
          2008-01-22 10:59:23,090 INFO [mylocation.controllers.ProductDetailsController] - <About to execute: Database Procedure>
          2008-01-22 10:59:23,090 INFO [mylocation.beans.MmsProduct] - <getActivationDate(): 2005-11-15>
          2008-01-22 10:59:23,090 INFO [mylocation.controllers.ProductDetailsController] - <formBackingObject command.getActivationDate(): 2005-11-15>
          2008-01-22 10:59:23,105 INFO [mylocation.controllers.ProductDetailsController] - <initBinder -- DATE FORMAT dd.mm.yyyy|| Locale: hr>
          2008-01-22 10:59:23,105 INFO [mylocation.controllers.ProductDetailsController] - <Date.class = class java.util.Date>
          2008-01-22 10:59:23,105 INFO [hr.pbz.popai.mms.controllers.ProductDetailsController] - <onBindOnNewForm command.getActivationDate():2005-11-15>
          2008-01-22 10:59:23,121 ERROR [org.apache.catalina.core.ContainerBase.[Catalina].[localhost].[/popai].[jsp]] - <Servlet.service() for servlet jsp threw exception>
          javax.servlet.jsp.el.ELException: Attempt to convert String "15.00.2005" to type "java.util.Date", but there is no PropertyEditor for that type
          To answer zour questions: yes, the class is java.util.Date.
          initBinder method is called. I put some logging in it to be sure.

          Clearly I don't quite understand how binding works, since I don-t know how to find where transformation really takes place.

          Comment


          • #6
            Well your dateformat is already screwed... 'mm' is for minutes in hour not for months (check the javadoc of SimpleDateFormat for that), so there is something wrong with your detection of the format, I would simply hardcode it.

            Post your controller and configuration.

            Comment


            • #7
              Ok,
              I found date format problem...

              Code:
              String dateFormatString = getText("defaultDateFormat", locale);
              In the property file it was dd.mm.yyyy, now it is ok, but the property editor still throws exception.

              Comment


              • #8
                Originally posted by Hippo
                In the property file it was dd.mm.yyyy, now it is ok, but the property editor still throws exception.
                What exception?! If you don't tell which exception it is quite useless. If it still is the same as before that isn't thrown by your PropertyEditor! It clearly states that a PropertyEditor isn't registered for java.util.Date (hence my question of you did register your PropertyEditor correctly!).

                As stated in my previous post.

                Originally posted by mdeinum
                Post your controller and configuration.

                Comment


                • #9
                  So now it is working.

                  First problem was wrong date format in properties file for locale.

                  The other was the exception:
                  Code:
                  2008-01-22 12:53:57,318 ERROR [org.apache.catalina.core.ContainerBase.[Catalina].[localhost].[/popai].[popaiDispatcher]] - <Servlet.service() for servlet popaiDispatcher threw exception>
                  javax.servlet.jsp.el.ELException: Attempt to convert String "15.11.2005" to type "java.util.Date", but there is no PropertyEditor for that type
                  occurs on something like this

                  Code:
                  <input type="text" name="${status.expression}" value="<fmt:formatDate value="${status.value}" pattern="dd.MM.yyyy."/>"
                  Conclusion: you can't put ${status.value} in <fmt:formatDate>...

                  I didn't know that.

                  I replaced that line with
                  Code:
                  <input type="text" name="${status.expression}" value="<fmt:formatDate value="${command.activationDate}" pattern="dd.MM.yyyy."/>"
                  and now it works.

                  So now both problems went away.

                  Thanks for replies!

                  Comment


                  • #10
                    Why use the fmt?! You already have a PropertyEditor taking care of that! You simply need to put ${status.value} inside your value remove the fmt tag.

                    Code:
                    <input type="text" name="${status.expression}" value="${status.value}"/>

                    Comment


                    • #11
                      Yes, you are right. I don't need it...

                      But there were times when I was desperate, so I tried anythig I could think of...

                      Thanks again.

                      Comment


                      • #12
                        I seem to have the same problem with putting a date in a <form:input> when viewing a page through a simpleformcontroller with the page being the page retrieved through the GET. In formBackingObject() i instantiatie some object based on a parameter in the request.

                        in the controller:
                        Code:
                        	protected void initBinder(HttpServletRequest request,
                        			ServletRequestDataBinder binder) throws Exception {
                        		DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
                        		CustomDateEditor editor = new CustomDateEditor(df, false);
                        		binder.registerCustomEditor(Date.class, editor);
                        	}
                        obviously I'd like to use the normal formula in the jsp file (form= spring form tld):
                        Code:
                        <form:input path="dateStart"/>
                        but that doesnt seem to work as it just outputs the date in the toString format.

                        So i used the suggested option:
                        Code:
                           <spring:bind path="dateStart">
                        	<input type="text" id="${status.expression}" name="${status.expression}" value="${status.value}"/>
                        </spring:bind>
                        Doesn't show the text in the input field as formatted date.

                        The suggested use of of the <fmt:formatDate> does work, but I cannot believe I can't use the normal form:input. It just seems to much hassel to be rite.

                        Why isnt the formatting done when I use a <form:input> tag with a bound path. I'm so missing something..
                        Last edited by Leftwing; Jul 14th, 2008, 10:35 AM.

                        Comment


                        • #13
                          Don't return a new ModelAndView with a model you yourself constructed, that will kill all the PropertyEditors, old/new values.

                          Comment


                          • #14
                            Originally posted by Marten Deinum View Post
                            Don't return a new ModelAndView with a model you yourself constructed, that will kill all the PropertyEditors, old/new values.
                            hehe you must get really bored by the answering on the same kind of questions every time. I bet you heard this one very often as well: I'm not returning a new model (for as far as i know)


                            Code:
                            // some import statements etc
                            ...
                            
                            public class OrderOverviewController extends CancellableFormController {
                            
                            	private OrderDao orderDao;
                            
                            	public OrderOverviewController() {
                            		setCommandClass(OrderObj.class);
                            	}
                            
                            	public void setOrderDao(OrderDao orderDao) {
                            		this.orderDao = orderDao;
                            	}
                            
                            	public OrderDao getOrderDao() {
                            		return orderDao;
                            	}
                            
                            	/*
                            	 * (non-Javadoc)
                            	 * 
                            	 * @see
                            	 * org.springframework.web.servlet.mvc.CancellableFormController#onCancel
                            	 * (java.lang.Object)
                            	 */
                            	@Override
                            	protected ModelAndView onCancel(Object command) throws Exception {
                            		return new ModelAndView("redirect:orderList.htm");
                            	}
                            
                            	/*
                            	 * (non-Javadoc)
                            	 * 
                            	 * @see
                            	 * org.springframework.web.servlet.mvc.SimpleFormController#onSubmit(javax
                            	 * .servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse,
                            	 * java.lang.Object, org.springframework.validation.BindException)
                            	 */
                            	@SuppressWarnings("unchecked")
                            	@Override
                            	protected ModelAndView onSubmit(HttpServletRequest request,
                            			HttpServletResponse response, Object command, BindException errors)
                            			throws Exception {
                            		Map<String, Object> model = errors.getModel();
                            		OrderObj order = (OrderObj) command;
                            
                            		// persist
                            		getOrderDao().save(order);
                            		// reset the order?
                            		model.put("order", order);
                            		
                            		// return to own view
                            		return new ModelAndView(getSuccessView(), model);
                            	}
                            
                            	/*
                            	 * (non-Javadoc)
                            	 * 
                            	 * @see
                            	 * org.springframework.web.servlet.mvc.AbstractFormController#formBackingObject
                            	 * (javax.servlet.http.HttpServletRequest)
                            	 */
                            	@Override
                            	protected Object formBackingObject(HttpServletRequest request)
                            			throws Exception {
                            		if (isCancelRequest(request))
                            			return super.formBackingObject(request);
                            
                            		return getOrderDao().getOrder(
                            				ServletRequestUtils.getIntParameter(request, "id"));
                            	}
                            
                            	/*
                            	 * (non-Javadoc)
                            	 * 
                            	 * @see
                            	 * org.springframework.web.servlet.mvc.SimpleFormController#referenceData
                            	 * (javax.servlet.http.HttpServletRequest, java.lang.Object,
                            	 * org.springframework.validation.Errors)
                            	 */
                            	@Override
                            	protected Map<String, Object> referenceData(HttpServletRequest request,
                            			Object order, Errors errors) throws Exception {
                            		HashMap<String, Object> model = new HashMap<String, Object>();
                            		model.put("order", order);
                            		return model;
                            	}
                            
                            	/*
                            	 * (non-Javadoc)
                            	 * 
                            	 * @see
                            	 * org.springframework.web.servlet.mvc.BaseCommandController#suppressBinding
                            	 * (javax.servlet.http.HttpServletRequest)
                            	 */
                            	@Override
                            	protected boolean suppressBinding(HttpServletRequest request) {
                            		return isCancelRequest(request);
                            	}
                            
                            	/*
                            	 * (non-Javadoc)
                            	 * 
                            	 * @see
                            	 * org.springframework.web.servlet.mvc.BaseCommandController#initBinder(
                            	 * javax.servlet.http.HttpServletRequest,
                            	 * org.springframework.web.bind.ServletRequestDataBinder)
                            	 */
                            	@Override
                            	protected void initBinder(HttpServletRequest request,
                            			ServletRequestDataBinder binder) throws Exception {
                            		DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
                            		CustomDateEditor editor = new CustomDateEditor(df, false);
                            		binder.registerCustomEditor(Date.class, editor);
                            	}
                            
                            	/* (non-Javadoc)
                            	 * @see org.springframework.web.servlet.mvc.BaseCommandController#onBindAndValidate(javax.servlet.http.HttpServletRequest, java.lang.Object, org.springframework.validation.BindException)
                            	 */
                            	@Override
                            	protected void onBindAndValidate(HttpServletRequest request,
                            			Object command, BindException errors) throws Exception {
                            		LogFactory.getLog(this.getClass()).info(errors);
                            		super.onBindAndValidate(request, command, errors);
                            	}
                            
                            }

                            Comment


                            • #15
                              hm okay.. referenceData returns a new model. would that be the problem? lets see..

                              edit --
                              that doesnt seem the problem as this errors object isnt the BindErrors object but some other validation errors object. Does not support the getModel method..
                              Last edited by Leftwing; Jul 14th, 2008, 10:51 AM. Reason: checked..

                              Comment

                              Working...
                              X