Close

Spring Framework - DataBinder Examples

Spring Framework 

This example shows, how to use DataBinder to do string input to bean property settings. This is considered a higher level alternative to BeanWrapperImpl.

package com.logicbig.example;

public class TestBean {
private int anInt;

public int getAnInt () {
return anInt;
}

public void setAnInt (int anInt) {
this.anInt = anInt;
}

@Override
public String toString () {
return "TestBean{anInt=" + anInt + '}';
}
}

DataBinder setting bean properties:

package com.logicbig.example;

import org.springframework.beans.MutablePropertyValues;
import org.springframework.validation.DataBinder;

public class DataBinderExample {
public static void main (String[] args) {

MutablePropertyValues mpv = new MutablePropertyValues();
mpv.add("anInt", "10");

TestBean testBean = new TestBean();
DataBinder db = new DataBinder(testBean);

db.bind(mpv);
System.out.println(testBean);

}
}

Output

TestBean{anInt=10}
Original Post




Capturing binding results.

package com.logicbig.example;

import org.springframework.beans.MutablePropertyValues;
import org.springframework.validation.DataBinder;

public class DataBinderUsingBindingResultExample {
public static void main (String[] args) {

MutablePropertyValues mpv = new MutablePropertyValues();
mpv.add("anInt", "10x"); // 10x cannot be converted to int type

TestBean testBean = new TestBean();
DataBinder db = new DataBinder(testBean);

db.bind(mpv);
db.getBindingResult().getAllErrors().stream().forEach(System.out::println);
System.out.println(testBean);

}
}

Output

Field error in object 'target' on field 'anInt': rejected value [10x]; codes [typeMismatch.target.anInt,typeMismatch.anInt,typeMismatch.int,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [target.anInt,anInt]; arguments []; default message [anInt]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'int' for property 'anInt'; nested exception is java.lang.NumberFormatException: For input string: "10x"]
TestBean{anInt=0}
Original Post




This example shows how to use ConversionService with DataBinder and a custom converter

package com.logicbig.example;

import org.springframework.beans.MutablePropertyValues;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.support.DefaultConversionService;
import org.springframework.validation.DataBinder;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;

public class ConversionServiceWithDataBinderExample {
public static void main (String[] args) {

MutablePropertyValues mpv = new MutablePropertyValues();
mpv.add("date", new Date());

DataBinder dataBinder = new DataBinder(new MyObject());
DefaultConversionService service = new DefaultConversionService();
service.addConverter(new DateToLocalDateTimeConverter());
//commenting the following line will not populate date field
dataBinder.setConversionService(service);

dataBinder.bind(mpv);
dataBinder.getBindingResult()
.getModel()
.entrySet()
.forEach(System.out::println);
}

private static class MyObject {
private LocalDateTime date;

public LocalDateTime getDate () {
return date;
}

public void setDate (LocalDateTime date) {
this.date = date;
}

@Override
public String toString () {
return "MyObject{" +
"date=" + date +
'}';
}
}

private static class DateToLocalDateTimeConverter
implements Converter<Date, LocalDateTime> {

@Override
public LocalDateTime convert (Date source) {
return LocalDateTime.ofInstant(source.toInstant(),
ZoneId.systemDefault());
}
}
}

Output

target=MyObject{date=2017-05-01T16:07:51.548}




This example shows how to use ConversionService with DataBinder and a custom converter

package com.logicbig.example;

import org.springframework.beans.MutablePropertyValues;
import org.springframework.core.convert.support.DefaultConversionService;
import org.springframework.validation.DataBinder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

public class ConversionServiceWithDataBinderExample {
public static void main (String[] args) throws ParseException {

MutablePropertyValues mpv = new MutablePropertyValues();

Date date = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a")
.parse("01/20/2022 00:00:00 AM");
mpv.add("date", date);

DataBinder dataBinder = new DataBinder(new MyObject());
DefaultConversionService service = new DefaultConversionService();
service.addConverter(new DateToLocalDateTimeConverter());
//commenting the following line will not populate date field
dataBinder.setConversionService(service);

dataBinder.bind(mpv);
dataBinder.getBindingResult()
.getModel()
.entrySet()
.forEach(System.out::println);
}

}

Output

target=MyObject{date=2022-01-20T00:00}
org.springframework.validation.BindingResult.target=org.springframework.validation.BeanPropertyBindingResult: 0 errors
package com.logicbig.example;

import java.time.LocalDateTime;

public class MyObject {
private LocalDateTime date;

public LocalDateTime getDate() {
return date;
}

public void setDate(LocalDateTime date) {
this.date = date;
}

@Override
public String toString() {
return "MyObject{" +
"date=" + date +
'}';
}
}
package com.logicbig.example;

import org.springframework.core.convert.converter.Converter;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;

public class DateToLocalDateTimeConverter
implements Converter<Date, LocalDateTime> {

@Override
public LocalDateTime convert(Date source) {
return LocalDateTime.ofInstant(source.toInstant(),
ZoneId.systemDefault());
}
}
Original Post

This example shows how to use DefaultFormattingConversionService with DataBinder and a custom formatter

package com.logicbig.example;

import org.springframework.beans.MutablePropertyValues;
import org.springframework.format.support.DefaultFormattingConversionService;
import org.springframework.validation.DataBinder;

import java.time.ZoneId;

public class ConversionServiceWithDataBinderExample {
public static void main(String[] args) {

MutablePropertyValues mpv = new MutablePropertyValues();
mpv.add("dateAtTargetTimeZone", "Thu, 25 Aug 2016 08:59:00 GMT");

DataBinder dataBinder = new DataBinder(new MyObject());
DefaultFormattingConversionService service = new DefaultFormattingConversionService();
service.addFormatter(new RFC1123LocalDateTimeFormatter(ZoneId.of("America/Chicago")));
dataBinder.setConversionService(service);

dataBinder.bind(mpv);
dataBinder.getBindingResult()
.getModel()
.entrySet()
.forEach(System.out::println);
}

}

Output

target=MyObject{dateAtTargetTimeZone=2016-08-25T03:59}
org.springframework.validation.BindingResult.target=org.springframework.validation.BeanPropertyBindingResult: 0 errors
package com.logicbig.example;

import java.time.LocalDateTime;

public class MyObject {
private LocalDateTime dateAtTargetTimeZone;

public LocalDateTime getDateAtTargetTimeZone() {
return dateAtTargetTimeZone;
}

public void setDateAtTargetTimeZone(LocalDateTime dateAtTargetTimeZone) {
this.dateAtTargetTimeZone = dateAtTargetTimeZone;
}

@Override
public String toString() {
return "MyObject{" +
"dateAtTargetTimeZone=" + dateAtTargetTimeZone +
'}';
}
}
package com.logicbig.example;

import org.springframework.format.Formatter;

import java.text.ParseException;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class RFC1123LocalDateTimeFormatter
implements Formatter<LocalDateTime> {

private ZoneId targetZoneId;

public RFC1123LocalDateTimeFormatter(ZoneId targetZoneId) {
this.targetZoneId = targetZoneId;
}

@Override
public LocalDateTime parse(String text, Locale locale) throws ParseException {
return ZonedDateTime.parse(text, DateTimeFormatter.RFC_1123_DATE_TIME)
.withZoneSameInstant(targetZoneId)
.toLocalDateTime();
}

@Override
public String print(LocalDateTime object, Locale locale) {
return object.format(DateTimeFormatter.RFC_1123_DATE_TIME);
}
}
Original Post




See Also