01: /*
02: * Copyright 2002-2006 the original author or authors.
03: *
04: * Licensed under the Apache License, Version 2.0 (the "License");
05: * you may not use this file except in compliance with the License.
06: * You may obtain a copy of the License at
07: *
08: * http://www.apache.org/licenses/LICENSE-2.0
09: *
10: * Unless required by applicable law or agreed to in writing, software
11: * distributed under the License is distributed on an "AS IS" BASIS,
12: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13: * See the License for the specific language governing permissions and
14: * limitations under the License.
15: */
16:
17: package org.springframework.validation;
18:
19: import java.util.Map;
20:
21: import org.springframework.util.Assert;
22:
23: /**
24: * Convenience methods for looking up BindingResults in a model Map.
25: *
26: * @author Juergen Hoeller
27: * @since 2.0
28: * @see BindingResult#MODEL_KEY_PREFIX
29: */
30: public abstract class BindingResultUtils {
31:
32: /**
33: * Find the BindingResult for the given name in the given model.
34: * @param model the model to search
35: * @param name the name of the target object to find a BindingResult for
36: * @return the BindingResult, or <code>null</code> if none found
37: * @throws IllegalStateException if the attribute found is not of type BindingResult
38: */
39: public static BindingResult getBindingResult(Map model, String name) {
40: Assert.notNull(model, "Model map must not be null");
41: Assert.notNull(name, "Name must not be null");
42: Object attr = model.get(BindingResult.MODEL_KEY_PREFIX + name);
43: if (attr != null && !(attr instanceof BindingResult)) {
44: throw new IllegalStateException(
45: "BindingResult attribute is not of type BindingResult: "
46: + attr);
47: }
48: return (BindingResult) attr;
49: }
50:
51: /**
52: * Find a required BindingResult for the given name in the given model.
53: * @param model the model to search
54: * @param name the name of the target object to find a BindingResult for
55: * @return the BindingResult (never <code>null</code>)
56: * @throws IllegalStateException if no BindingResult found
57: */
58: public static BindingResult getRequiredBindingResult(Map model,
59: String name) {
60: BindingResult bindingResult = getBindingResult(model, name);
61: if (bindingResult == null) {
62: throw new IllegalStateException(
63: "No BindingResult attribute found for name '"
64: + name
65: + "'- have you exposed the correct model?");
66: }
67: return bindingResult;
68: }
69:
70: }
|