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.lang.Nullable; 022import org.springframework.util.Assert; 023 024/** 025 * Convenience methods for looking up BindingResults in a model Map. 026 * 027 * @author Juergen Hoeller 028 * @since 2.0 029 * @see BindingResult#MODEL_KEY_PREFIX 030 */ 031public abstract class BindingResultUtils { 032 033 /** 034 * Find the BindingResult for the given name in the given model. 035 * @param model the model to search 036 * @param name the name of the target object to find a BindingResult for 037 * @return the BindingResult, or {@code null} if none found 038 * @throws IllegalStateException if the attribute found is not of type BindingResult 039 */ 040 @Nullable 041 public static BindingResult getBindingResult(Map<?, ?> model, String name) { 042 Assert.notNull(model, "Model map must not be null"); 043 Assert.notNull(name, "Name must not be null"); 044 Object attr = model.get(BindingResult.MODEL_KEY_PREFIX + name); 045 if (attr != null && !(attr instanceof BindingResult)) { 046 throw new IllegalStateException("BindingResult attribute is not of type BindingResult: " + attr); 047 } 048 return (BindingResult) attr; 049 } 050 051 /** 052 * Find a required BindingResult for the given name in the given model. 053 * @param model the model to search 054 * @param name the name of the target object to find a BindingResult for 055 * @return the BindingResult (never {@code null}) 056 * @throws IllegalStateException if no BindingResult found 057 */ 058 public static BindingResult getRequiredBindingResult(Map<?, ?> model, String name) { 059 BindingResult bindingResult = getBindingResult(model, name); 060 if (bindingResult == null) { 061 throw new IllegalStateException("No BindingResult attribute found for name '" + name + 062 "'- have you exposed the correct model?"); 063 } 064 return bindingResult; 065 } 066 067}