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