3

How can I convert a string from a form input (easyui-datetimebox, in case) to a Calendar property in an object in Controller, autobinded by Spring?

I've read http://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/validation.html but I couldn't find anything nearly right-to-the-point there.

JSP:

<input id="DeadLineDate"
  class="easyui-datetimebox" 
  name="DeadLineDate"
  value="${SessionDeadLineDate}"
  data-options="formatter:myformatter,
                parser:myparser
/>

When submited, Spring validation throws an error:

Failed to convert property value of type java.lang.String to required type java.util.Calendar for property DeadLineDate; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [java.util.Calendar] for property DeadLineDate: no matching editors or conversion strategy found.

PS: Spring 3

Edit: adding controller's method to perform operation:

@Controller
@RequestMapping("/project/MaintainProjectFrm")
@SessionAttributes({"project","SessionDeadLineDate"})
public class MaintainProjectController {

    /* ... many methods... */

    @RequestMapping(params = "update", method = RequestMethod.POST, produces={"text/plain; charset=UTF-8"})
    public String update(@ModelAttribute("project") Project project, 
                            BindingResult result, 
                                    SessionStatus status, 
                                        ModelMap model,
                                            HttpServletRequest req,
                                                HttpServletResponse resp) throws IOException {

        projectValidator.validate(project, result);

        if (result.hasErrors()) {
             //has errors, in this case, that one shown in text above, which is rendered again in view (JSP)
            return "/project/MaintainProjectFrm";
        } else {

            try{
                mpService.updateProject(project);
            }
            catch(Exception e){
                resp.setStatus(500);
                resp.getWriter().write("Error updating project: " + e.getMessage());
                return "/project/MaintainProjectFrm";
            }

            status.setComplete();

        }
    }

    /* ... yet other methods ... */
}
3
  • 1
    Can we see your handler method? Commented Jan 21, 2014 at 14:10
  • @SotiriosDelimanolis: sure, done! Commented Jan 21, 2014 at 14:23
  • I'd use @RequestParam in order to receive DeadLineDate from view, and manually create a Calendar object on it, updating the Project object. But of course it's not the ellegant way to do so! I'd like to know if in a certain maneer Spring is able of autobinding a Calendar from this property. Commented Jan 21, 2014 at 14:32

3 Answers 3

8

I'm assuming your Project class has the field DeadLineDate (fields should start with a lowercase character).

Annotate it with @DateTimeFormat like so

@DateTimeFormat(pattern = "yyyy/MM/dd") // or whatever pattern you want
private Calendar DeadLineDate;

Your client will then need to send the appropriate pattern.

Sign up to request clarification or add additional context in comments.

2 Comments

Excellent!!! I was expecting more about sth like @gregor wrote, but definitely it was the simplest way. It's wonderful that Spring has this flexibility. And yes, I'm surely using java pattern. My propertie was "miscapitalized" while translating stuff names from Portuguese. Thanks a lot!
Great aproach !
4

You have two possibilities to achieve this: You can use a PropertyEditor

@InitBinder
public void initBinder(WebDataBinder binder) {
    binder.registerCustomEditor(Calendar.class, new PropertyEditorSupport() {
        @Override
        public void setAsText(String text) throws IllegalArgumentException {
            setValue(parseDate());
        }

        private Calendar parseDate() {
            try {
                Calendar cal = Calendar.getInstance();
                SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
                cal.setTime(sdf.parse("Mon Mar 14 16:02:37 GMT 2011"));
                return cal;
            } catch (ParseException e) {
                 return null;
            }
        }
    });
}

For Documentation see this and this.

Or you can use spring conversion service. For this see: "Spring 3 Type Conversion".

4 Comments

thanks for your answer (I've voted up). But I rather used Sotirios Delimanolis approach, which was the simplest solution for my case. Regards!
@Alex: Does the accepted solution works for spring 3.1? For my case, this answer saved me! Thanks gregor. +1
@sarwar026, I'm actually upgrading to Spring 3.6, and I was not able to test it yet.
@Alex: I see. I will try to upgrade my one too. Thanks!
-1

try this like Sotirios Delimanolis said..

@DateTimeFormat(pattern = "yyyy/MM/dd") // or whatever pattern you want
private Calendar DeadLineDate;

and finally, add this to pom.xml:

<dependency>
   <groupId>joda-time</groupId>
   <artifactId>joda-time</artifactId>
   <version>2.3</version>
</dependency>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.