001/* 002 * Copyright 2002-2017 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.web.servlet.mvc.method.annotation; 018 019import java.util.Map; 020 021import javax.servlet.ServletRequest; 022 023import org.springframework.beans.MutablePropertyValues; 024import org.springframework.lang.Nullable; 025import org.springframework.web.bind.ServletRequestDataBinder; 026import org.springframework.web.servlet.HandlerMapping; 027 028/** 029 * Subclass of {@link ServletRequestDataBinder} that adds URI template variables 030 * to the values used for data binding. 031 * 032 * @author Rossen Stoyanchev 033 * @since 3.1 034 */ 035public class ExtendedServletRequestDataBinder extends ServletRequestDataBinder { 036 037 /** 038 * Create a new instance, with default object name. 039 * @param target the target object to bind onto (or {@code null} 040 * if the binder is just used to convert a plain parameter value) 041 * @see #DEFAULT_OBJECT_NAME 042 */ 043 public ExtendedServletRequestDataBinder(@Nullable Object target) { 044 super(target); 045 } 046 047 /** 048 * Create a new instance. 049 * @param target the target object to bind onto (or {@code null} 050 * if the binder is just used to convert a plain parameter value) 051 * @param objectName the name of the target object 052 * @see #DEFAULT_OBJECT_NAME 053 */ 054 public ExtendedServletRequestDataBinder(@Nullable Object target, String objectName) { 055 super(target, objectName); 056 } 057 058 059 /** 060 * Merge URI variables into the property values to use for data binding. 061 */ 062 @Override 063 @SuppressWarnings("unchecked") 064 protected void addBindValues(MutablePropertyValues mpvs, ServletRequest request) { 065 String attr = HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE; 066 Map<String, String> uriVars = (Map<String, String>) request.getAttribute(attr); 067 if (uriVars != null) { 068 uriVars.forEach((name, value) -> { 069 if (mpvs.contains(name)) { 070 if (logger.isWarnEnabled()) { 071 logger.warn("Skipping URI variable '" + name + 072 "' because request contains bind value with same name."); 073 } 074 } 075 else { 076 mpvs.addPropertyValue(name, value); 077 } 078 }); 079 } 080 } 081 082}