Problems with date field in spring

2

I'm not able to retrieve a date field from my jsp.

The field looks like this:

<label for="txtDataEvento">Data do Evento</label> 
			<input type="text" name="data" class="form-control" id="txtDataEvento" value="${evento.data}" />

The type of my date field in VO is Calendar and I have already put the annotation that has been suggested in some forums.

@DateTimeFormat(pattern="dd/MM/yyyy")
    private Calendar data;

I still keep getting the following error message:

  

Field error in object 'event' on field 'data': rejected value   [06/20/2015]; codes   [typeMismatch.events.data, typeMismatch.data, typeMismatch.java.util.Calendar, typeMismatch];   arguments   [org.springframework.context.support.DefaultMessageSourceResolvable:

Could someone help?

    
asked by anonymous 05.06.2015 / 15:13

1 answer

1

Brunão, you will probably need to create a PropertyEditor

What happens is that Spring does not know how to convert this string that is displayed on the screen - dd / mm / yyyy directly to one Instance of Calendar

For Spring 3.X

@InitBinder
public void initBinder(WebDataBinder binder) {
    binder.registerCustomEditor(Calendar.class, new PropertyEditorSupport() {
        @Override
        public void setAsText(String value) {
            try {
                Calendar cal = Calendar.getInstance();
                cal.setTime(new SimpleDateFormat("dd-MM-yyyy").parse(value));
                setValue(cal);
            } catch (ParseException e) {
                setValue(null);
            }
        }

        @Override
        public String getAsText() {
            if (getValue() == null) {
                return "";
            }
            return new SimpleDateFormat("dd-MM-yyyy").format(((Calendar) getValue()).getTime());
        }
    });
}

If you can, take a look also at this reference documentation:

link

It will kill your problem.

    
05.06.2015 / 17:06