001/* 002 * Copyright 2002-2012 the original author or authors. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * https://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 017package org.springframework.validation; 018 019import java.util.Map; 020 021import org.springframework.util.Assert; 022 023/** 024 * Convenience methods for looking up BindingResults in a model Map. 025 * 026 * @author Juergen Hoeller 027 * @since 2.0 028 * @see BindingResult#MODEL_KEY_PREFIX 029 */ 030public abstract class BindingResultUtils { 031 032 /** 033 * Find the BindingResult for the given name in the given model. 034 * @param model the model to search 035 * @param name the name of the target object to find a BindingResult for 036 * @return the BindingResult, or {@code null} if none found 037 * @throws IllegalStateException if the attribute found is not of type BindingResult 038 */ 039 public static BindingResult getBindingResult(Map<?, ?> model, String name) { 040 Assert.notNull(model, "Model map must not be null"); 041 Assert.notNull(name, "Name must not be null"); 042 Object attr = model.get(BindingResult.MODEL_KEY_PREFIX + name); 043 if (attr != null && !(attr instanceof BindingResult)) { 044 throw new IllegalStateException("BindingResult attribute is not of type BindingResult: " + attr); 045 } 046 return (BindingResult) attr; 047 } 048 049 /** 050 * Find a required BindingResult for the given name in the given model. 051 * @param model the model to search 052 * @param name the name of the target object to find a BindingResult for 053 * @return the BindingResult (never {@code null}) 054 * @throws IllegalStateException if no BindingResult found 055 */ 056 public static BindingResult getRequiredBindingResult(Map<?, ?> model, String name) { 057 BindingResult bindingResult = getBindingResult(model, name); 058 if (bindingResult == null) { 059 throw new IllegalStateException("No BindingResult attribute found for name '" + name + 060 "'- have you exposed the correct model?"); 061 } 062 return bindingResult; 063 } 064 065}