Problems with date field in spring

Asked

Viewed 623 times

2

I am unable to retrieve a date field from my jsp.

The peasant is 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 down the note that was suggested in some forums.

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

Even so I still keep getting the following error message:

Field error in Object 'event' on field 'data': Rejected value [20/06/2015]; codes [typeMismatch.evento.data,typeMismatch.data,typeMismatch.java.util.Calendar,typeMismatch]; Arguments [org.springframework.context.support.Defaultmessagesourceresolvable:

Could someone help?

  • Which version of Spring you’re using?

1 answer

1


Brunon, you will probably need to create a Propertyeditor

How Spring Binds a Data/Field Request?

What happens is that Spring doesn’t know how to convert this String that is shown on the screen - dd/MM/yyyy directly to a Calendar Instance

To 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:

http://docs.spring.io/spring/docs/2.5.x/reference/mvc.html#mvc-Ann-initbinder

Will kill your problem.

  • Valew Filipe.... worked a beauty!!!!!! Thank you very much...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.