added bind template / field binder

This commit is contained in:
Keith Donald
2009-07-26 20:23:51 +00:00
parent ccb0a30169
commit a66aa8c320
8 changed files with 218 additions and 128 deletions

View File

@@ -22,15 +22,17 @@ import java.util.Map;
* @author Keith Donald
* @since 3.0
* @see #bind(Map)
* @param <M> The type of model this binder binds to
*/
public interface Binder {
public interface Binder<M> {
/**
* Bind submitted field values.
* @param fieldValues the field values to bind
* @param model the model to bind to
* @return the results of the binding operation
* @throws MissingFieldException when the fieldValues Map is missing required fields
*/
BindingResults bind(Map<String, ? extends Object> fieldValues);
BindingResults bind(Map<String, ? extends Object> fieldValues, M model);
}

View File

@@ -15,8 +15,6 @@
*/
package org.springframework.model.binder.support;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.springframework.context.MessageSource;
@@ -27,28 +25,34 @@ import org.springframework.model.binder.MissingFieldException;
import org.springframework.util.Assert;
/**
* A base {@link Binder binder} implementation designed for subclassing.
* Base Binder implementation that defines common structural elements.
* Subclasses should parameterized & implement {@link #bind(Map, Object)}.
* @author Keith Donald
* @since 3.0
* @see #setRequiredFields(String[])
* @see #setMessageSource(MessageSource)
* @see #bind(Map)
* @see #bind(Map, Object)
* @see #createBindTemplate()
*/
public abstract class AbstractBinder implements Binder {
public abstract class AbstractBinder<M> implements Binder<M> {
private String[] requiredFields;
private BindTemplate bindTemplate;
private MessageSource messageSource;
public AbstractBinder() {
bindTemplate = createBindTemplate();
}
/**
* Configure the fields for which values must be present in each bind attempt.
* @param fieldNames the required field names
* @see MissingFieldException
*/
public void setRequiredFields(String[] fieldNames) {
this.requiredFields = fieldNames;
bindTemplate.setRequiredFields(fieldNames);
}
/**
* Configure the MessageSource that resolves localized {@link BindingResult} alert messages.
* @param messageSource the message source
@@ -58,69 +62,30 @@ public abstract class AbstractBinder implements Binder {
this.messageSource = messageSource;
}
// implementing Binder
public abstract BindingResults bind(Map<String, ? extends Object> fieldValues, M model);
public BindingResults bind(Map<String, ? extends Object> fieldValues) {
fieldValues = filter(fieldValues);
checkRequired(fieldValues);
ArrayListBindingResults results = new ArrayListBindingResults(fieldValues.size());
for (Map.Entry<String, ? extends Object> fieldValue : fieldValues.entrySet()) {
results.add(bindField(fieldValue.getKey(), fieldValue.getValue()));
}
return results;
}
// subclassing hooks
// subclass hooks
/**
* Hook subclasses may use to filter the source values to bind.
* This hook allows the binder to pre-process the field values before binding occurs.
* For example, a Binder might insert empty or default values for fields that are not present.
* As another example, a Binder might collapse multiple source values into a single source value.
* Default implementation simply returns the fieldValues Map unchanged.
* @param fieldValues the original fieldValues Map provided by the caller
* @return the filtered fieldValues Map that will be used to bind
* Create the template defining the bulk-binding algorithm.
* Subclasses may override to customize the algorithm.
*/
protected Map<String, ? extends Object> filter(Map<String, ? extends Object> fieldValues) {
return fieldValues;
protected BindTemplate createBindTemplate() {
return new BindTemplate();
}
/**
* The template defining the bulk-binding algorithm.
*/
protected BindTemplate getBindTemplate() {
return bindTemplate;
}
/**
* The configured MessageSource that resolves binding result alert messages.
*/
protected MessageSource getMessageSource() {
return messageSource;
}
/**
* Hook method subclasses override to perform a single field binding.
* @param name the field name
* @param value the field value
* @return the binding result
*/
protected abstract BindingResult bindField(String name, Object value);
// internal helpers
private void checkRequired(Map<String, ? extends Object> fieldValues) {
if (requiredFields == null) {
return;
}
List<String> missingRequired = new ArrayList<String>();
for (String required : requiredFields) {
boolean found = false;
for (String property : fieldValues.keySet()) {
if (property.equals(required)) {
found = true;
}
}
if (!found) {
missingRequired.add(required);
}
}
if (!missingRequired.isEmpty()) {
throw new MissingFieldException(missingRequired, fieldValues);
}
}
}

View File

@@ -0,0 +1,80 @@
/*
* Copyright 2004-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.model.binder.support;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.springframework.model.binder.BindingResults;
import org.springframework.model.binder.MissingFieldException;
/**
* A template that encapsulates the general bulk-binding algorithm.
* @author Keith Donald
* @since 3.0
* @see #setRequiredFields(String[])
* @see #bind(Map)
*/
public class BindTemplate {
private String[] requiredFields;
/**
* Configure the fields for which values must be present in each bind attempt.
* @param fieldNames the required field names
* @see MissingFieldException
*/
public void setRequiredFields(String[] fieldNames) {
this.requiredFields = fieldNames;
}
// implementing Binder
public BindingResults bind(Map<String, ? extends Object> fieldValues, FieldBinder fieldBinder) {
checkRequired(fieldValues);
ArrayListBindingResults results = new ArrayListBindingResults(fieldValues.size());
for (Map.Entry<String, ? extends Object> fieldValue : fieldValues.entrySet()) {
results.add(fieldBinder.bind(fieldValue.getKey(), fieldValue.getValue()));
}
return results;
}
// internal helpers
private void checkRequired(Map<String, ? extends Object> fieldValues) {
if (requiredFields == null) {
return;
}
List<String> missingRequired = new ArrayList<String>();
for (String required : requiredFields) {
boolean found = false;
for (String property : fieldValues.keySet()) {
if (property.equals(required)) {
found = true;
}
}
if (!found) {
missingRequired.add(required);
}
}
if (!missingRequired.isEmpty()) {
throw new MissingFieldException(missingRequired, fieldValues);
}
}
}

View File

@@ -0,0 +1,34 @@
/*
* Copyright 2004-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.model.binder.support;
import org.springframework.model.binder.BindingResult;
/**
* BindTemplate callback interface for binding a single field value.
* @author Keith Donald
* @see BindTemplate#bind(java.util.Map, BindCallback)
*/
public interface FieldBinder {
/**
* Bind a single field.
* @param fieldName the field name
* @param value the field value
* @return the binding result
*/
BindingResult bind(String fieldName, Object value);
}

View File

@@ -18,62 +18,78 @@ package org.springframework.model.ui.support;
import java.util.Map;
import org.springframework.context.MessageSource;
import org.springframework.model.binder.Binder;
import org.springframework.model.binder.BindingResult;
import org.springframework.model.binder.BindingResults;
import org.springframework.model.binder.support.AbstractBinder;
import org.springframework.model.binder.support.AlertBindingResult;
import org.springframework.model.binder.support.FieldBinder;
import org.springframework.model.binder.support.FieldNotEditableResult;
import org.springframework.model.binder.support.FieldNotFoundResult;
import org.springframework.model.ui.BindingStatus;
import org.springframework.model.ui.FieldModel;
import org.springframework.model.ui.FieldNotFoundException;
import org.springframework.model.ui.PresentationModel;
import org.springframework.util.Assert;
/**
* A generic {@link Binder binder} suitable for use in most environments.
* Binds field values to PresentationModel objects.
* @author Keith Donald
* @since 3.0
* @see #setMessageSource(MessageSource)
* @see #setRequiredFields(String[])
* @see #bind(Map)
* @see #bind(Map, PresentationModel)
*/
public class PresentationModelBinder extends AbstractBinder {
public class PresentationModelBinder extends AbstractBinder<PresentationModel> {
private PresentationModel presentationModel;
public PresentationModelBinder(PresentationModel presentationModel) {
Assert.notNull(presentationModel, "The PresentationModel is required");
this.presentationModel = presentationModel;
public BindingResults bind(Map<String, ? extends Object> fieldValues, PresentationModel model) {
fieldValues = filter(fieldValues, model);
return getBindTemplate().bind(fieldValues, new FieldModelBinder(model, getMessageSource()));
}
// subclassing hooks
/**
* Get the model for the field.
* @param fieldName
* @return the field model
* @throws NoSuchFieldException if no such field exists
* Filter the fields to bind.
* Allows for pre-processing the fieldValues Map before any binding occurs.
* For example, you might insert empty or default values for fields that are not present.
* As another example, you might collapse multiple fields into a single field.
* Default implementation simply returns the fieldValues Map unchanged.
* @param fieldValues the original fieldValues Map provided by the caller
* @return the filtered fieldValues Map that will be used to bind
*/
protected FieldModel getFieldModel(String fieldName) {
return presentationModel.getFieldModel(fieldName);
protected Map<String, ? extends Object> filter(Map<String, ? extends Object> fieldValues, PresentationModel model) {
return fieldValues;
}
// internal helpers
private static class FieldModelBinder implements FieldBinder {
private PresentationModel presentationModel;
private MessageSource messageSource;
public FieldModelBinder(PresentationModel presentationModel, MessageSource messageSource) {
this.presentationModel = presentationModel;
this.messageSource = messageSource;
}
public BindingResult bind(String fieldName, Object value) {
FieldModel field;
try {
field = presentationModel.getFieldModel(fieldName);
} catch (FieldNotFoundException e) {
return new FieldNotFoundResult(fieldName, value, messageSource);
}
if (!field.isEditable()) {
return new FieldNotEditableResult(fieldName, value, messageSource);
} else {
field.applySubmittedValue(value);
if (field.getBindingStatus() == BindingStatus.DIRTY) {
field.commit();
}
return new AlertBindingResult(fieldName, value, field.getStatusAlert());
}
}
}
protected BindingResult bindField(String name, Object value) {
FieldModel field;
try {
field = getFieldModel(name);
} catch (FieldNotFoundException e) {
return new FieldNotFoundResult(name, value, getMessageSource());
}
if (!field.isEditable()) {
return new FieldNotEditableResult(name, value, getMessageSource());
} else {
field.applySubmittedValue(value);
if (field.getBindingStatus() == BindingStatus.DIRTY) {
field.commit();
}
return new AlertBindingResult(name, value, field.getStatusAlert());
}
}
}

View File

@@ -28,6 +28,7 @@ import org.springframework.model.ui.PresentationModel;
* @since 3.0
* @see #setDefaultPrefix(String)
* @see #setPresentPrefix(String)
* @see #filter(Map, PresentationModel)
*/
public class WebBinder extends PresentationModelBinder {
@@ -35,14 +36,6 @@ public class WebBinder extends PresentationModelBinder {
private String presentPrefix = "_";
/**
* Creates a new web binder for the model object.
* @param model the model object containing properties this binder will bind to
*/
public WebBinder(PresentationModel bindingFactory) {
super(bindingFactory);
}
/**
* Configure the prefix used to detect the default value for a field when no value is submitted.
* Default is '!'.
@@ -61,7 +54,7 @@ public class WebBinder extends PresentationModelBinder {
}
@Override
protected Map<String, ? extends Object> filter(Map<String, ? extends Object> fieldValues) {
protected Map<String, ? extends Object> filter(Map<String, ? extends Object> fieldValues, PresentationModel model) {
LinkedHashMap<String, Object> filteredValues = new LinkedHashMap<String, Object>();
for (Map.Entry<String, ? extends Object> entry : fieldValues.entrySet()) {
String field = entry.getKey();
@@ -74,7 +67,7 @@ public class WebBinder extends PresentationModelBinder {
} else if (field.startsWith(presentPrefix)) {
field = field.substring(presentPrefix.length());
if (!fieldValues.containsKey(field) && !fieldValues.containsKey(defaultPrefix + field)) {
value = getEmptyValue(getFieldModel(field));
value = getEmptyValue(model.getFieldModel(field));
filteredValues.put(field, value);
}
} else {