001/* 002 * Copyright 2002-2018 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.accept; 018 019import java.util.Map; 020 021import org.springframework.http.MediaType; 022import org.springframework.lang.Nullable; 023import org.springframework.util.Assert; 024import org.springframework.web.context.request.NativeWebRequest; 025 026/** 027 * Strategy that resolves the requested content type from a query parameter. 028 * The default query parameter name is {@literal "format"}. 029 * 030 * <p>You can register static mappings between keys (i.e. the expected value of 031 * the query parameter) and MediaType's via {@link #addMapping(String, MediaType)}. 032 * As of 5.0 this strategy also supports dynamic lookups of keys via 033 * {@link org.springframework.http.MediaTypeFactory#getMediaType}. 034 * 035 * @author Rossen Stoyanchev 036 * @since 3.2 037 */ 038public class ParameterContentNegotiationStrategy extends AbstractMappingContentNegotiationStrategy { 039 040 private String parameterName = "format"; 041 042 043 /** 044 * Create an instance with the given map of file extensions and media types. 045 */ 046 public ParameterContentNegotiationStrategy(Map<String, MediaType> mediaTypes) { 047 super(mediaTypes); 048 } 049 050 051 /** 052 * Set the name of the parameter to use to determine requested media types. 053 * <p>By default this is set to {@code "format"}. 054 */ 055 public void setParameterName(String parameterName) { 056 Assert.notNull(parameterName, "'parameterName' is required"); 057 this.parameterName = parameterName; 058 } 059 060 public String getParameterName() { 061 return this.parameterName; 062 } 063 064 065 @Override 066 @Nullable 067 protected String getMediaTypeKey(NativeWebRequest request) { 068 return request.getParameter(getParameterName()); 069 } 070 071}