From eae18f18cb3796f82443fdc500ab191ebec55cea Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Sat, 14 Nov 2026 10:41:25 -0800 Subject: [PATCH 01/21] Expose the URL mapping that handles a request as its best matching handler UrlMappingsHandlerMapping now sets HandlerMapping.BEST_MATCHING_HANDLER_ATTRIBUTE to the UrlMappingInfo it returns, as Spring MVC's own handler mappings set it for the handler they find, and takes it off the request once the dispatch completes, with an interceptor first in the chain so that it completes last, whichever interceptor stops the request. A dispatch another handler mapping handles in the meantime, such as a forward to a Spring MVC endpoint, keeps the attribute it set. Content negotiation can then tell a request a URL mapping handles from one a Spring MVC endpoint handles, and from what Spring Security negotiates after the dispatch. The version lookup no longer fails for a request whose response type resolves to none. --- .../mvc/UrlMappingsHandlerMapping.groovy | 36 ++++- .../mvc/UrlMappingsHandlerMappingSpec.groovy | 135 +++++++++++++++++- 2 files changed, 164 insertions(+), 7 deletions(-) diff --git a/grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMapping.groovy b/grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMapping.groovy index 0bcd0d52f9c..a4a673b371a 100644 --- a/grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMapping.groovy +++ b/grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMapping.groovy @@ -74,6 +74,7 @@ class UrlMappingsHandlerMapping extends AbstractHandlerMapping { // Both are stateless, so one shared instance each rather than two allocations per request. private static final HandlerInterceptor OBSERVATION_ROUTE_HANDLER = new ObservationRouteHandler() private static final HandlerInterceptor ERROR_HANDLING_HANDLER = new ErrorHandlingHandler() + private static final HandlerInterceptor HANDLED_REQUEST_HANDLER = new HandledRequestHandler() /** * Whether to resolve a "_method" parameter on a POST into the overridden request method while matching @@ -164,6 +165,8 @@ class UrlMappingsHandlerMapping extends AbstractHandlerMapping { // before(), so that a failure in one is reported under the route that failed chain.addInterceptor(webRequestInterceptorCount, OBSERVATION_ROUTE_HANDLER) chain.addInterceptor(ERROR_HANDLING_HANDLER) + // First, so that it completes last, whichever interceptor stops the request + chain.addInterceptor(0, HANDLED_REQUEST_HANDLER) return chain } @@ -178,8 +181,22 @@ class UrlMappingsHandlerMapping extends AbstractHandlerMapping { return match == null && !rootCause.is(thrown) ? urlMappingsHolder.matchStatusCode(status, rootCause) : match } + /** + * The mapping that handles the request, which is also the request's + * {@link org.springframework.web.servlet.HandlerMapping#BEST_MATCHING_HANDLER_ATTRIBUTE}, as each of Spring MVC's + * handler mappings sets it for the handler it finds, until the dispatch completes, so that what Spring MVC + * negotiates for the request while a URL mapping handles it can tell that one does. + */ @Override protected Object getHandlerInternal(HttpServletRequest request) throws Exception { + Object handler = matchHandler(request) + if (handler != null) { + request.setAttribute(BEST_MATCHING_HANDLER_ATTRIBUTE, handler) + } + return handler + } + + private Object matchHandler(HttpServletRequest request) { def includedInfo = WebUtils.isInclude(request) ? request.getAttribute(INCLUDED_MAPPING_INFO) : null if (includedInfo != null) { @@ -273,8 +290,9 @@ class UrlMappingsHandlerMapping extends AbstractHandlerMapping { protected String findRequestedVersion(GrailsWebRequest currentRequest) { String version = currentRequest.getHeader(HttpHeaders.ACCEPT_VERSION) if (!version && mimeTypeResolver) { + // none where the request accepts no configured type, as with grails.mime.negotiation.spring MimeType mimeType = mimeTypeResolver.resolveResponseMimeType(currentRequest) - version = mimeType.version + version = mimeType?.version } return version } @@ -331,6 +349,22 @@ class UrlMappingsHandlerMapping extends AbstractHandlerMapping { } } + /** + * Takes the mapping off the request as its best matching handler once the dispatch it handles completes, so that + * what negotiates for the request afterwards, such as Spring Security's filters for an exception the dispatch left + * unresolved, or the handler mapping of an error dispatch, does not take it for a request a URL mapping handles. + */ + @CompileStatic + static class HandledRequestHandler implements HandlerInterceptor { + + @Override + void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { + if (request.getAttribute(BEST_MATCHING_HANDLER_ATTRIBUTE).is(handler)) { + request.removeAttribute(BEST_MATCHING_HANDLER_ATTRIBUTE) + } + } + } + static class ErrorHandlingHandler implements HandlerInterceptor { @Override diff --git a/grails-web-url-mappings/src/test/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMappingSpec.groovy b/grails-web-url-mappings/src/test/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMappingSpec.groovy index a8c84a72805..72233cada8b 100644 --- a/grails-web-url-mappings/src/test/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMappingSpec.groovy +++ b/grails-web-url-mappings/src/test/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMappingSpec.groovy @@ -21,6 +21,8 @@ package org.grails.web.mapping.mvc import java.sql.SQLException import jakarta.servlet.DispatcherType +import jakarta.servlet.http.HttpServletRequest +import jakarta.servlet.http.HttpServletResponse import grails.artefact.Artefact import grails.core.DefaultGrailsApplication @@ -29,6 +31,7 @@ import grails.util.GrailsWebMockUtil import grails.web.Action import grails.web.HyphenatedUrlConverter import grails.web.mapping.AbstractUrlMappingsSpec +import grails.web.mime.MimeTypeResolver import org.grails.web.errors.GrailsWrappedRuntimeException import org.grails.web.mapping.DefaultUrlMappingData import org.grails.web.mapping.DefaultUrlMappingInfo @@ -44,6 +47,7 @@ import org.springframework.web.context.request.WebRequestInterceptor import org.springframework.web.context.support.StaticWebApplicationContext import org.springframework.web.filter.ServerHttpObservationFilter import org.springframework.web.servlet.HandlerInterceptor +import org.springframework.web.servlet.HandlerMapping import org.springframework.web.servlet.handler.WebRequestHandlerInterceptorAdapter import org.springframework.web.servlet.view.InternalResourceView import spock.lang.Issue @@ -352,7 +356,7 @@ class UrlMappingsHandlerMappingSpec extends AbstractUrlMappingsSpec { result.view.getUrl() == "/index.html" } - void "the handler chain keeps WebRequestInterceptors first, then the route, and appends the error handling last"() { + void "the handler chain completes the handled request last, keeps WebRequestInterceptors first, then the route, and appends the error handling last"() { given: "a handler mapping with both a WebRequestInterceptor and an ordinary HandlerInterceptor" def handlerMapping = handlerMapping() def plainInterceptor = new HandlerInterceptor() {} @@ -370,13 +374,16 @@ class UrlMappingsHandlerMappingSpec extends AbstractUrlMappingsSpec { webRequest.request.setRequestURI("/foo/bar") def interceptors = handlerMapping.getHandler(webRequest.request).interceptorList - then: "the WebRequestInterceptor is adapted and ordered first, ahead of ordinary interceptors" - interceptors[0] instanceof WebRequestHandlerInterceptorAdapter + then: "the handled request is completed by the first interceptor, which completes last whichever stops the request" + interceptors[0].class.simpleName == 'HandledRequestHandler' + + and: "the WebRequestInterceptor is adapted and ordered next, ahead of ordinary interceptors" + interceptors[1] instanceof WebRequestHandlerInterceptorAdapter interceptors.contains(plainInterceptor) and: "the route is set ahead of the ordinary interceptors, which can fail, and the error handling is last" - interceptors[1].class.simpleName == 'ObservationRouteHandler' - interceptors.indexOf(plainInterceptor) > 1 + interceptors[2].class.simpleName == 'ObservationRouteHandler' + interceptors.indexOf(plainInterceptor) > 2 interceptors[-1].class.simpleName == 'ErrorHandlingHandler' } @@ -394,7 +401,8 @@ class UrlMappingsHandlerMappingSpec extends AbstractUrlMappingsSpec { second.request.setRequestURI("/foo/bar") def secondChain = handlerMapping.getHandler(second.request).interceptorList - then: "both chains end with the very same interceptor instances" + then: "both chains start and end with the very same interceptor instances" + firstChain[0].is(secondChain[0]) firstChain[-1].is(secondChain[-1]) firstChain[-2].is(secondChain[-2]) } @@ -647,6 +655,121 @@ class UrlMappingsHandlerMappingSpec extends AbstractUrlMappingsSpec { context.pathPattern == '/foo/bar' } + void 'the mapping that handles a request is its best matching handler, as a Spring MVC handler mapping sets it'() { + given: + def grailsApplication = new DefaultGrailsApplication(FooController) + grailsApplication.initialise() + def handler = new UrlMappingsHandlerMapping(new GrailsControllerUrlMappings(grailsApplication, getUrlMappingsHolder { + '/foo/bar'(controller: 'foo', action: 'bar') + '/'(view: '/index') + })) + def request = GrailsWebMockUtil.bindMockWebRequest().request + + when: 'a request a controller mapping matches' + request.requestURI = '/foo/bar' + def chain = handler.getHandler(request) + + then: + request.getAttribute(HandlerMapping.BEST_MATCHING_HANDLER_ATTRIBUTE).is(chain.handler) + chain.handler instanceof GrailsControllerUrlMappingInfo + + when: 'a request a view mapping matches' + request.removeAttribute(UrlMappingsHandlerMapping.MATCHED_REQUEST) + request.requestURI = '/' + chain = handler.getHandler(request) + + then: + request.getAttribute(HandlerMapping.BEST_MATCHING_HANDLER_ATTRIBUTE).is(chain.handler) + chain.handler.viewName == '/index' + } + + void 'the mapping is no longer the best matching handler once its dispatch completes, #how'() { + given: + def grailsApplication = new DefaultGrailsApplication(FooController) + grailsApplication.initialise() + def handler = new UrlMappingsHandlerMapping(new GrailsControllerUrlMappings(grailsApplication, getUrlMappingsHolder { + '/foo/bar'(controller: 'foo', action: 'bar') + })) + boolean proceeds = proceed + handler.setHandlerInterceptors([new HandlerInterceptor() { + @Override + boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object mapped) { + proceeds + } + }] as HandlerInterceptor[]) + def webRequest = GrailsWebMockUtil.bindMockWebRequest() + def request = webRequest.request + request.requestURI = '/foo/bar' + def chain = handler.getHandler(request) + + when: 'the dispatcher completes, in reverse, the interceptors that proceeded, and not one that stopped the request' + def completed = chain.interceptorList.takeWhile { interceptor -> + interceptor.preHandle(request, webRequest.response, chain.handler) + } + completed.reverseEach { interceptor -> interceptor.afterCompletion(request, webRequest.response, chain.handler, null) } + + then: + request.getAttribute(HandlerMapping.BEST_MATCHING_HANDLER_ATTRIBUTE) == null + + where: + how | proceed + 'after the action' | true + 'also where an interceptor stops the request' | false + } + + void 'a dispatch another handler mapping handles meanwhile keeps the best matching handler it set'() { + given: + def grailsApplication = new DefaultGrailsApplication(FooController) + grailsApplication.initialise() + def handler = new UrlMappingsHandlerMapping(new GrailsControllerUrlMappings(grailsApplication, getUrlMappingsHolder { + '/foo/bar'(controller: 'foo', action: 'bar') + })) + def webRequest = GrailsWebMockUtil.bindMockWebRequest() + def request = webRequest.request + request.requestURI = '/foo/bar' + def chain = handler.getHandler(request) + + when: 'the action forwards to a handler of Spring MVC, which takes the attribute' + def springHandler = new Object() + request.setAttribute(HandlerMapping.BEST_MATCHING_HANDLER_ATTRIBUTE, springHandler) + chain.interceptorList.reverseEach { interceptor -> interceptor.afterCompletion(request, webRequest.response, chain.handler, null) } + + then: + request.getAttribute(HandlerMapping.BEST_MATCHING_HANDLER_ATTRIBUTE).is(springHandler) + } + + void 'a request no mapping matches keeps the best matching handler another handler mapping set'() { + given: + def handler = new UrlMappingsHandlerMapping(getUrlMappingsHolder { + '/foo/bar'(controller: 'foo', action: 'bar') + }) + def request = GrailsWebMockUtil.bindMockWebRequest().request + def springHandler = new Object() + request.setAttribute(HandlerMapping.BEST_MATCHING_HANDLER_ATTRIBUTE, springHandler) + request.requestURI = '/spring/endpoint' + + expect: + handler.getHandler(request) == null + request.getAttribute(HandlerMapping.BEST_MATCHING_HANDLER_ATTRIBUTE).is(springHandler) + } + + void 'a request that accepts no configured type is matched on the version of its Accept-Version header alone'() { + given: 'a resolver that resolves no type for the response, as Spring negotiation does for such a request' + def grailsApplication = new DefaultGrailsApplication(FooController) + grailsApplication.initialise() + def handler = new UrlMappingsHandlerMapping(new GrailsControllerUrlMappings(grailsApplication, getUrlMappingsHolder { + '/foo/bar'(controller: 'foo', action: 'bar') + })) + handler.mimeTypeResolver = Stub(MimeTypeResolver) { + resolveResponseMimeType(_) >> null + } + def request = GrailsWebMockUtil.bindMockWebRequest().request + request.requestURI = '/foo/bar' + + expect: + handler.getHandler(request).handler.actionName == 'bar' + } + void cleanup() { RequestContextHolder.resetRequestAttributes() } From 88b004d0ed2f827732f6fcda5877ef520491a908 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Sat, 14 Nov 2026 10:41:45 -0800 Subject: [PATCH 02/21] Resolve Grails formats through Spring MVC's content negotiation (#16698) The opt-in grails.mime.negotiation.spring (default false in Grails 10) resolves request.format, response.format, withFormat and the format respond writes in with Spring MVC's ContentNegotiationManager, as the formats grails.mime.types gives the media types it resolves: - The Accept header is read by Spring MVC's manager, with its strategies and spring.mvc.contentnegotiation.*, in its order: quality, then specificity, then the order of the header. The text/xml merge and the +xml preference are gone. - A type with the +json or +xml suffix that no configured type names is the json or xml format, as Spring MVC's converters write such types; this extends the rule Grails 9 had for the problem types of RFC 9457. - */* is the all format, also where it is not configured. Another wildcard, such as text/*, is a type of the all format that withFormat answers with its first block, and respond with the first of the action's formats, whose format has a type compatible with it. - A request that accepts no configured type, or whose Accept header Spring cannot read, has no format: response.format is null, respond answers 406 and withFormat runs its * block or none. - The format parameter and URL extensions are kept, ahead of Spring MVC's strategies; an unknown format is not acceptable and all leaves the format to the Accept header. request.format reads Content-Type with Spring's parser. The format parameter, URL extensions and the grails.mime Accept header settings are installed into Spring MVC's manager, by a post-processor that replaces the mvcContentNegotiationManager bean with the setting only, as strategies that apply while a URL mapping handles the request, so that what Spring MVC writes for an action, such as a ResponseEntity or a ProblemDetail, is negotiated as Grails resolves its format. Spring MVC endpoints and Spring Security, before a mapping has matched the request, negotiate as before, and GrailsContentNegotiationStrategy is still no Spring ContentNegotiationStrategy bean. A web unit test marks the request of the action it calls as handled by a URL mapping, as in an application. Without the setting, every answer is that of Grails 9. --- .../main/groovy/grails/config/Settings.groovy | 18 + .../web/api/MimeTypesApiSupport.groovy | 94 +++- .../web/mime/MimeTypesConfiguration.groovy | 31 +- ...eptHeaderContentNegotiationStrategy.groovy | 73 +++ .../GrailsContentNegotiationManager.groovy | 90 ++++ ...tentNegotiationManagerPostProcessor.groovy | 69 +++ .../GrailsContentNegotiationStrategy.groovy | 377 +++++++++++++- ...ilsFormatContentNegotiationStrategy.groovy | 74 +++ .../mime/HttpServletRequestExtension.groovy | 10 +- .../mime/HttpServletResponseExtension.groovy | 54 +-- .../mime/MimeTypesConfigurationSpec.groovy | 2 +- .../mime/SpringFormatNegotiationSpec.groovy | 459 ++++++++++++++++++ .../RequestAndResponseMimeTypesApiSpec.groovy | 23 +- .../artefact/controller/RestResponder.groovy | 31 +- .../MigrationSettingsMetadataSpec.groovy | 1 + .../SpringFormatNegotiationRespondSpec.groovy | 234 +++++++++ .../testing/web/GrailsWebUnitTest.groovy | 6 + ...itional-spring-configuration-metadata.json | 6 + 18 files changed, 1584 insertions(+), 68 deletions(-) create mode 100644 grails-mimetypes/src/main/groovy/org/grails/web/mime/GrailsAcceptHeaderContentNegotiationStrategy.groovy create mode 100644 grails-mimetypes/src/main/groovy/org/grails/web/mime/GrailsContentNegotiationManager.groovy create mode 100644 grails-mimetypes/src/main/groovy/org/grails/web/mime/GrailsContentNegotiationManagerPostProcessor.groovy create mode 100644 grails-mimetypes/src/main/groovy/org/grails/web/mime/GrailsFormatContentNegotiationStrategy.groovy create mode 100644 grails-mimetypes/src/test/groovy/org/grails/web/mime/SpringFormatNegotiationSpec.groovy create mode 100644 grails-test-suite-web/src/test/groovy/grails/rest/web/SpringFormatNegotiationRespondSpec.groovy diff --git a/grails-core/src/main/groovy/grails/config/Settings.groovy b/grails-core/src/main/groovy/grails/config/Settings.groovy index c5f7bf615f9..339a6c75bac 100644 --- a/grails-core/src/main/groovy/grails/config/Settings.groovy +++ b/grails-core/src/main/groovy/grails/config/Settings.groovy @@ -212,6 +212,24 @@ interface Settings { */ String MIME_DISABLE_ACCEPT_HEADER_FOR_USER_AGENTS_XHR = 'grails.mime.disable.accept.header.userAgentsXhr' + /** + * Whether {@code request.format}, {@code response.format}, {@code withFormat} and the format {@code respond} writes + * in are resolved with Spring MVC's content negotiation manager, which also applies the {@code grails.mime} rules + * Grails keeps to what Spring MVC writes for the requests a URL mapping handles, rather than by Grails' own rules. + * Defaults to {@link #MIME_NEGOTIATION_SPRING_DEFAULT}. + * + * @since 10.0 + */ + String MIME_NEGOTIATION_SPRING = 'grails.mime.negotiation.spring' + + /** + * The default of {@link #MIME_NEGOTIATION_SPRING}, as a property placeholder reads it: {@code false} in Grails 10, + * which keeps the negotiation of Grails 9. + * + * @since 10.0 + */ + String MIME_NEGOTIATION_SPRING_DEFAULT = 'false' + /** * The default scope for controllers */ diff --git a/grails-mimetypes/src/main/groovy/org/grails/plugins/web/api/MimeTypesApiSupport.groovy b/grails-mimetypes/src/main/groovy/org/grails/plugins/web/api/MimeTypesApiSupport.groovy index 86622bfcb9e..378032de564 100644 --- a/grails-mimetypes/src/main/groovy/org/grails/plugins/web/api/MimeTypesApiSupport.groovy +++ b/grails-mimetypes/src/main/groovy/org/grails/plugins/web/api/MimeTypesApiSupport.groovy @@ -27,6 +27,7 @@ import jakarta.servlet.http.HttpServletResponse import grails.web.mime.MimeType import org.grails.plugins.web.mime.FormatInterceptor +import org.grails.web.mime.GrailsContentNegotiationStrategy import org.grails.web.servlet.mvc.GrailsWebRequest import org.grails.web.util.GrailsApplicationAttributes @@ -39,6 +40,9 @@ import org.grails.web.util.GrailsApplicationAttributes @CompileStatic class MimeTypesApiSupport { + /** What {@link #resolveAllFormat(Object, LinkedHashMap, MimeType)} answers where no block is of a compatible format. */ + protected static final Object NO_FORMAT = new Object() + def T withFormat(HttpServletRequest request, Closure callable) { return (T) withFormatInternal(request, getDefinedFormats(callable)) } @@ -52,33 +56,38 @@ class MimeTypesApiSupport { String format = lookupFormat(formatProvider) if (formats) { if (format == 'all') { - result = resolveAllFormat(formatProvider, formats) + result = resolveAllFormat(formatProvider, formats, acceptedWildcard(formatProvider)) + if (!result.is(NO_FORMAT)) { + return result + } + result = null + } + // if the format has been specified then use that + if (formats.containsKey(format)) { + result = getResponseForFormat(formats[format], format, formatProvider) } + // otherwise look for the best match else { - // if the format has been specified then use that - if (formats.containsKey(format)) { - result = getResponseForFormat(formats[format], format, formatProvider) - } - // otherwise look for the best match - else { - boolean matchFound = false - for (MimeType mime in lookupMimeTypes(formatProvider)) { - if (formats.containsKey(mime.extension)) { - matchFound = true - result = getResponseForFormat(formats[mime.extension], mime.extension, formatProvider) - break - } - else { - if (mime.extension == 'all') { + boolean matchFound = false + for (MimeType mime in lookupMimeTypes(formatProvider)) { + if (formats.containsKey(mime.extension)) { + matchFound = true + result = getResponseForFormat(formats[mime.extension], mime.extension, formatProvider) + break + } + else { + if (mime.extension == 'all') { + result = resolveAllFormat(formatProvider, formats, mime) + if (!result.is(NO_FORMAT)) { matchFound = true - result = resolveAllFormat(formatProvider, formats) break } + result = null } } - if (!matchFound && formats.containsKey('*')) { - result = getResponseForFormat(formats['*'], format, formatProvider) - } + } + if (!matchFound && formats.containsKey('*')) { + result = getResponseForFormat(formats['*'], format, formatProvider) } } } @@ -106,6 +115,51 @@ class MimeTypesApiSupport { getResponseForFormat(formats[formatKey], format, formatProvider) } + /** + * Resolves a type of the {@code all} format the request accepts: {@code */*} as any format, and, with + * {@code grails.mime.negotiation.spring}, a wildcard such as {@code text/*}, which it resolves an {@code Accept} header + * to, as the {@code *} block or else the first block of a format with a type compatible with it, as Spring MVC answers + * a wildcard with the first of its candidates that is compatible with it. + * + * @param formatProvider the request or the response + * @param formats the blocks, by format + * @param accepted the type of the {@code all} format + * @return the result of the block, or {@link #NO_FORMAT} where none is of a format compatible with the wildcard + * @since 10.0 + */ + protected Object resolveAllFormat(formatProvider, LinkedHashMap formats, MimeType accepted) { + if (accepted == null || accepted.extension != 'all' || accepted.name == MimeType.ALL.name || formats.containsKey('*')) { + return resolveAllFormat(formatProvider, formats) + } + GrailsContentNegotiationStrategy strategy = GrailsContentNegotiationStrategy.forRequest(request(formatProvider)) + if (!strategy.springNegotiation) { + return resolveAllFormat(formatProvider, formats) + } + String compatible = formats.keySet().find { String format -> strategy.acceptsFormat(accepted, format) } + return compatible != null ? getResponseForFormat(formats[compatible], compatible, formatProvider) : NO_FORMAT + } + + /** + * The wildcard the {@code all} format of the response stands for, where it is the first type the request accepts + * rather than a format the request names or {@code withFormat} selected, which is saved as the response format: only + * {@code grails.mime.negotiation.spring} resolves a wildcard such as {@code text/*} to it, and does not save it. It is + * read from the types the request accepts, which saves no type for the response. + */ + private MimeType acceptedWildcard(formatProvider) { + if (!(formatProvider instanceof HttpServletResponse)) { + return null + } + HttpServletRequest request = GrailsWebRequest.lookup().currentRequest + if (request.getAttribute(GrailsApplicationAttributes.RESPONSE_FORMAT) != null) { + return null + } + return lookupMimeTypes(formatProvider)?.find { it } + } + + private static HttpServletRequest request(formatProvider) { + formatProvider instanceof HttpServletRequest ? (HttpServletRequest) formatProvider : GrailsWebRequest.lookup().currentRequest + } + @CompileStatic(TypeCheckingMode.SKIP) protected MimeType[] lookupMimeTypes(formatProvider) { formatProvider.mimeTypes diff --git a/grails-mimetypes/src/main/groovy/org/grails/plugins/web/mime/MimeTypesConfiguration.groovy b/grails-mimetypes/src/main/groovy/org/grails/plugins/web/mime/MimeTypesConfiguration.groovy index 64952768c2a..c336b6f884a 100644 --- a/grails-mimetypes/src/main/groovy/org/grails/plugins/web/mime/MimeTypesConfiguration.groovy +++ b/grails-mimetypes/src/main/groovy/org/grails/plugins/web/mime/MimeTypesConfiguration.groovy @@ -24,9 +24,12 @@ import groovy.transform.CompileStatic import groovy.transform.TypeCheckingMode import org.springframework.beans.factory.ObjectProvider +import org.springframework.beans.factory.annotation.Qualifier import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.context.annotation.Primary +import org.springframework.core.env.Environment +import org.springframework.web.accept.ContentNegotiationManager import grails.config.Config import grails.config.Settings @@ -37,6 +40,7 @@ import grails.web.mime.MimeTypeResolver import grails.web.mime.MimeUtility import org.grails.web.mime.DefaultMimeTypeResolver import org.grails.web.mime.DefaultMimeUtility +import org.grails.web.mime.GrailsContentNegotiationManagerPostProcessor import org.grails.web.mime.GrailsContentNegotiationStrategy import org.grails.web.mime.GrailsMimeTypesWebMvcConfigurer @@ -142,22 +146,43 @@ class MimeTypesConfiguration { * formats it registers with Spring MVC are those of the configuration: those * {@code grails.mime.types} declares, or the defaults where it declares none or * {@code grails.mime.mergeDefaults} adds them, which Spring MVC's content negotiation manager - * needs as it is created, and not those a {@code MimeTypeProvider} adds. + * needs as it is created, and not those a {@code MimeTypeProvider} adds. The strategy it builds resolves formats, + * with {@code grails.mime.negotiation.spring}, with Spring MVC's content negotiation manager, which is asked for + * once a request is negotiated, since it is created after the configurer. */ @Bean static GrailsMimeTypesWebMvcConfigurer grailsMimeTypesWebMvcConfigurer( - ObjectProvider mimeUtility, GrailsApplication grailsApplication) { + ObjectProvider mimeUtility, GrailsApplication grailsApplication, + @Qualifier(GrailsContentNegotiationStrategy.MVC_CONTENT_NEGOTIATION_MANAGER) + ObjectProvider contentNegotiationManager) { // A user agent that is not a regular expression is reported as the application starts, rather than by every // request, which builds the strategy once it is first asked for GrailsContentNegotiationStrategy.disabledUserAgentPatterns(grailsApplication.config) // The MIME types request.format and response.format resolve against as well + Supplier manager = () -> contentNegotiationManager.getIfAvailable() Supplier strategy = () -> - new GrailsContentNegotiationStrategy(mimeUtility.getObject().knownMimeTypes as MimeType[], grailsApplication.config) + new GrailsContentNegotiationStrategy(mimeUtility.getObject().knownMimeTypes as MimeType[], + grailsApplication.config, manager) Supplier formats = () -> configuredMimeTypes(grailsApplication.config, declaredMimeTypes(grailsApplication.config)) return new GrailsMimeTypesWebMvcConfigurer(strategy, formats) } + /** + * With {@code grails.mime.negotiation.spring}, has Spring MVC's content negotiation manager apply the + * {@code grails.mime} rules Grails keeps to the requests a URL mapping handles. Static, as a post-processor is + * created before the other beans, and the strategy it applies them with is that of the configurer, once a request + * is negotiated. + * + * @since 10.0 + */ + @Bean + static GrailsContentNegotiationManagerPostProcessor grailsContentNegotiationManagerPostProcessor( + Environment environment, ObjectProvider grailsMimeTypesWebMvcConfigurer) { + return new GrailsContentNegotiationManagerPostProcessor(environment, () -> + grailsMimeTypesWebMvcConfigurer.getObject().contentNegotiationStrategy) + } + /** * The MIME types the {@code mimeTypes} bean, and so the application's {@code MimeUtility}, starts from, before those * of the {@code MimeTypeProvider} beans. The formats registered with Spring MVC are those {@code grails.mime.types} diff --git a/grails-mimetypes/src/main/groovy/org/grails/web/mime/GrailsAcceptHeaderContentNegotiationStrategy.groovy b/grails-mimetypes/src/main/groovy/org/grails/web/mime/GrailsAcceptHeaderContentNegotiationStrategy.groovy new file mode 100644 index 00000000000..6edfed24860 --- /dev/null +++ b/grails-mimetypes/src/main/groovy/org/grails/web/mime/GrailsAcceptHeaderContentNegotiationStrategy.groovy @@ -0,0 +1,73 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.grails.web.mime + +import java.util.function.Supplier + +import groovy.transform.CompileStatic + +import jakarta.servlet.http.HttpServletRequest + +import org.springframework.http.MediaType +import org.springframework.web.HttpMediaTypeNotAcceptableException +import org.springframework.web.accept.HeaderContentNegotiationStrategy +import org.springframework.web.context.request.NativeWebRequest + +/** + * The strategy of Spring MVC's content negotiation manager that reads the {@code Accept} header in place of Spring MVC's + * own, and ignores it for a request a URL mapping handles where {@code grails.mime.use.accept.header} or + * {@code grails.mime.disable.accept.header.*} say so, so that what Spring MVC writes for it is in the format Grails + * resolves for it. Any other request, such as one a Spring MVC endpoint handles, is negotiated by the strategy it + * replaces. It is a {@link HeaderContentNegotiationStrategy}, so that it is found as Spring MVC's is. + * + * @since 10.0 + */ +@CompileStatic +class GrailsAcceptHeaderContentNegotiationStrategy extends HeaderContentNegotiationStrategy { + + private final HeaderContentNegotiationStrategy springStrategy + + private final Supplier grailsStrategy + + /** + * @param springStrategy the strategy of Spring MVC's manager that it replaces + * @param grailsStrategy supplies the strategy that resolves Grails formats, which Spring MVC's manager is created + * before + */ + GrailsAcceptHeaderContentNegotiationStrategy(HeaderContentNegotiationStrategy springStrategy, + Supplier grailsStrategy) { + this.springStrategy = springStrategy + this.grailsStrategy = grailsStrategy + } + + /** @return the strategy of Spring MVC's manager it replaces */ + HeaderContentNegotiationStrategy getSpringStrategy() { + return springStrategy + } + + @Override + List resolveMediaTypes(NativeWebRequest webRequest) throws HttpMediaTypeNotAcceptableException { + HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest) + if (request != null && GrailsContentNegotiationStrategy.handlesRequest(request) && + grailsStrategy.get().ignoresAcceptHeader(request)) { + return MEDIA_TYPE_ALL_LIST + } + return springStrategy.resolveMediaTypes(webRequest) + } +} diff --git a/grails-mimetypes/src/main/groovy/org/grails/web/mime/GrailsContentNegotiationManager.groovy b/grails-mimetypes/src/main/groovy/org/grails/web/mime/GrailsContentNegotiationManager.groovy new file mode 100644 index 00000000000..6c8aa49dba6 --- /dev/null +++ b/grails-mimetypes/src/main/groovy/org/grails/web/mime/GrailsContentNegotiationManager.groovy @@ -0,0 +1,90 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.grails.web.mime + +import java.util.function.Supplier + +import groovy.transform.CompileStatic + +import org.springframework.http.MediaType +import org.springframework.web.accept.ContentNegotiationManager +import org.springframework.web.accept.ContentNegotiationStrategy +import org.springframework.web.accept.HeaderContentNegotiationStrategy +import org.springframework.web.accept.MediaTypeFileExtensionResolver + +/** + * Spring MVC's content negotiation manager with {@code grails.mime.negotiation.spring}: its strategies, after the one + * that resolves the format a request a URL mapping handles names, and with the {@code Accept} header read by one that + * ignores it for such a request where the {@code grails.mime} settings say so. Any other request is negotiated as by + * Spring MVC's manager, whose formats and file extensions it answers with. + * + * @since 10.0 + */ +@CompileStatic +class GrailsContentNegotiationManager extends ContentNegotiationManager { + + private final ContentNegotiationManager springManager + + /** + * @param springManager Spring MVC's manager + * @param grailsStrategy supplies the strategy that resolves Grails formats, which Spring MVC's manager is created + * before + */ + GrailsContentNegotiationManager(ContentNegotiationManager springManager, + Supplier grailsStrategy) { + super(strategies(springManager, grailsStrategy)) + this.springManager = springManager + } + + /** @return Spring MVC's manager, whose strategies this one applies to the requests no URL mapping handles */ + ContentNegotiationManager getSpringManager() { + return springManager + } + + @Override + void addFileExtensionResolvers(MediaTypeFileExtensionResolver... resolvers) { + springManager.addFileExtensionResolvers(resolvers) + } + + @Override + List resolveFileExtensions(MediaType mediaType) { + return springManager.resolveFileExtensions(mediaType) + } + + @Override + List getAllFileExtensions() { + return springManager.allFileExtensions + } + + @Override + Map getMediaTypeMappings() { + return springManager.mediaTypeMappings + } + + private static List strategies(ContentNegotiationManager springManager, + Supplier grailsStrategy) { + List strategies = [new GrailsFormatContentNegotiationStrategy(grailsStrategy)] as List + for (ContentNegotiationStrategy strategy in springManager.strategies) { + strategies << (strategy instanceof HeaderContentNegotiationStrategy ? + new GrailsAcceptHeaderContentNegotiationStrategy((HeaderContentNegotiationStrategy) strategy, grailsStrategy) : + strategy) + } + return strategies + } +} diff --git a/grails-mimetypes/src/main/groovy/org/grails/web/mime/GrailsContentNegotiationManagerPostProcessor.groovy b/grails-mimetypes/src/main/groovy/org/grails/web/mime/GrailsContentNegotiationManagerPostProcessor.groovy new file mode 100644 index 00000000000..2299b6d562d --- /dev/null +++ b/grails-mimetypes/src/main/groovy/org/grails/web/mime/GrailsContentNegotiationManagerPostProcessor.groovy @@ -0,0 +1,69 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.grails.web.mime + +import java.util.function.Supplier + +import groovy.transform.CompileStatic + +import org.springframework.beans.BeansException +import org.springframework.beans.factory.config.BeanPostProcessor +import org.springframework.core.env.Environment +import org.springframework.web.accept.ContentNegotiationManager + +import grails.config.Settings + +/** + * With {@code grails.mime.negotiation.spring}, replaces Spring MVC's content negotiation manager with one that applies + * the {@code grails.mime} rules Grails keeps to the requests a URL mapping handles (see + * {@link GrailsContentNegotiationManager}), so that what Spring MVC writes for them, such as a {@code ResponseEntity} or + * a {@code ProblemDetail} an action returns or {@code respond} writes, is negotiated as Grails resolves their formats. + * Without it, Spring MVC's manager is left as it is. + * + * @since 10.0 + */ +@CompileStatic +class GrailsContentNegotiationManagerPostProcessor implements BeanPostProcessor { + + private final Environment environment + + private final Supplier grailsStrategy + + /** + * @param environment the environment the setting is read from + * @param grailsStrategy supplies the strategy that resolves Grails formats, which Spring MVC's manager is created + * before + */ + GrailsContentNegotiationManagerPostProcessor(Environment environment, + Supplier grailsStrategy) { + this.environment = environment + this.grailsStrategy = grailsStrategy + } + + @Override + Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { + if (beanName == GrailsContentNegotiationStrategy.MVC_CONTENT_NEGOTIATION_MANAGER && + bean instanceof ContentNegotiationManager && !(bean instanceof GrailsContentNegotiationManager) && + environment.getProperty(Settings.MIME_NEGOTIATION_SPRING, Boolean, + Boolean.valueOf(Settings.MIME_NEGOTIATION_SPRING_DEFAULT))) { + return new GrailsContentNegotiationManager((ContentNegotiationManager) bean, grailsStrategy) + } + return bean + } +} diff --git a/grails-mimetypes/src/main/groovy/org/grails/web/mime/GrailsContentNegotiationStrategy.groovy b/grails-mimetypes/src/main/groovy/org/grails/web/mime/GrailsContentNegotiationStrategy.groovy index 05dd5dabec8..68a18d7a4ec 100644 --- a/grails-mimetypes/src/main/groovy/org/grails/web/mime/GrailsContentNegotiationStrategy.groovy +++ b/grails-mimetypes/src/main/groovy/org/grails/web/mime/GrailsContentNegotiationStrategy.groovy @@ -18,6 +18,7 @@ */ package org.grails.web.mime +import java.util.function.Supplier import java.util.regex.Pattern import java.util.regex.PatternSyntaxException @@ -25,13 +26,33 @@ import groovy.transform.CompileStatic import jakarta.servlet.http.HttpServletRequest +import org.slf4j.Logger +import org.slf4j.LoggerFactory +import org.springframework.context.ApplicationContext +import org.springframework.http.InvalidMediaTypeException +import org.springframework.http.MediaType +import org.springframework.web.HttpMediaTypeNotAcceptableException +import org.springframework.web.accept.ContentNegotiationManager +import org.springframework.web.accept.ContentNegotiationStrategy +import org.springframework.web.accept.HeaderContentNegotiationStrategy +import org.springframework.web.context.request.ServletWebRequest +import org.springframework.web.context.support.WebApplicationContextUtils +import org.springframework.web.servlet.HandlerMapping + import grails.config.Config import grails.config.Settings +import grails.core.GrailsApplication import grails.web.http.HttpHeaders +import grails.web.mapping.UrlMappingInfo import grails.web.mime.MimeType +import grails.web.mime.MimeUtility +import org.grails.config.PropertySourcesConfig +import org.grails.web.servlet.mvc.GrailsWebRequest /** - * Resolves the MIME types of a request's {@code Accept} header under the {@code grails.mime} rules. + * Resolves the formats of a request: the MIME types of its {@code Accept} header under the {@code grails.mime} rules, + * or, with {@code grails.mime.negotiation.spring}, the media types Spring MVC's content negotiation manager resolves for + * it, as the formats {@code grails.mime.types} gives them. * It is deliberately not a Spring {@code ContentNegotiationStrategy}: Spring MVC keeps its own * negotiation, and Spring Security adopts any such bean it finds. * @@ -40,12 +61,43 @@ import grails.web.mime.MimeType @CompileStatic class GrailsContentNegotiationStrategy { + private static final Logger LOG = LoggerFactory.getLogger(GrailsContentNegotiationStrategy) + + /** The name of the bean Spring MVC's content negotiation manager is, which its handler adapter is given by name. */ + static final String MVC_CONTENT_NEGOTIATION_MANAGER = 'mvcContentNegotiationManager' + + private static final String FORMAT_PARAMETER = 'format' + + private static final String ALL_FORMAT = 'all' + + /** The formats a type with the structured syntax suffix of RFC 6839 of their name is a document of. */ + private static final Set SUFFIX_FORMATS = Set.of('json', 'xml') + private final MimeType[] mimeTypes private final boolean useAcceptHeader private final boolean useAcceptHeaderXhr private final List disableForUserAgents + private final boolean springNegotiation + private final Supplier contentNegotiationManager + + /** The media type of each configured MIME type, in its place, or {@code null} for one Spring cannot read. */ + private final MediaType[] mediaTypes GrailsContentNegotiationStrategy(MimeType[] mimeTypes, Config config) { + this(mimeTypes, config, null) + } + + /** + * @param mimeTypes the MIME types the formats are resolved against + * @param config the application's configuration + * @param contentNegotiationManager supplies Spring MVC's content negotiation manager, which, with + * {@code grails.mime.negotiation.spring}, the formats are resolved with; asked for each request, since the + * strategy is created before it; or {@code null}, or one that supplies none, for one that reads the + * {@code Accept} header alone, as Spring MVC's default does + * @since 10.0 + */ + GrailsContentNegotiationStrategy(MimeType[] mimeTypes, Config config, + Supplier contentNegotiationManager) { this.mimeTypes = mimeTypes this.useAcceptHeader = config.getProperty(Settings.MIME_USE_ACCEPT_HEADER, Boolean, true) this.useAcceptHeaderXhr = !config.getProperty( @@ -54,6 +106,10 @@ class GrailsContentNegotiationStrategy { false ) this.disableForUserAgents = disabledUserAgentPatterns(config) + this.springNegotiation = config.getProperty(Settings.MIME_NEGOTIATION_SPRING, Boolean, + Boolean.valueOf(Settings.MIME_NEGOTIATION_SPRING_DEFAULT)) + this.contentNegotiationManager = contentNegotiationManager + this.mediaTypes = mimeTypes.collect { MimeType mimeType -> mediaTypeOf(mimeType) } as MediaType[] } /** @@ -64,12 +120,27 @@ class GrailsContentNegotiationStrategy { return mimeTypes } + /** + * @return whether the formats are resolved with Spring MVC's content negotiation manager, as + * {@code grails.mime.negotiation.spring} says + * @since 10.0 + */ + boolean isSpringNegotiation() { + return springNegotiation + } + /** * @return the MIME types of the {@code Accept} header under the {@code grails.mime} rules, without * any {@code format} applied. This is what {@code response.mimeTypes}, and so {@code withFormat} - * when the format has no block of its own, resolves. + * when the format has no block of its own, resolves. With {@code grails.mime.negotiation.spring}, they are the + * configured types the media types Spring MVC's content negotiation manager resolves for the request stand for, in + * its order, without the format the request names, and none where the request accepts no configured type. */ MimeType[] resolveAcceptedMimeTypes(HttpServletRequest request) { + if (springNegotiation) { + List requested = requestedMediaTypes(request) + return requested == null ? new MimeType[0] : acceptedMimeTypes(requested) + } String acceptHeader = resolveAcceptHeader(request) MimeType[] resolved = new DefaultAcceptHeaderParser(mimeTypes).parse(acceptHeader) if (!acceptHeader) { @@ -81,17 +152,311 @@ class GrailsContentNegotiationStrategy { return resolved } - private String resolveAcceptHeader(HttpServletRequest request) { - if (!useAcceptHeader) { + /** + * The MIME type a format a request names, with the {@code format} parameter or a URL extension, or that + * {@code withFormat} selected, stands for. + * + * @param format the format + * @return its first configured type; for a format that is not configured, the first configured type, as Grails 9 + * answers, or, with {@code grails.mime.negotiation.spring}, {@code null}, since the request accepts no + * configured type + * @since 10.0 + */ + MimeType resolveFormat(Object format) { + MimeType mimeType = mimeTypes.find { MimeType configured -> configured.extension == format } + if (mimeType != null || springNegotiation) { + return mimeType + } + return mimeTypes.find { it } + } + + /** + * The format the request names with its {@code format} parameter or a URL extension, which overrides its + * {@code Accept} header: with {@code grails.mime.negotiation.spring}, the first value of the parameter, as Spring MVC + * reads a parameter it negotiates with, unless it names no type, as the {@code all} format does, which leaves the + * negotiation to the {@code Accept} header, as Spring MVC's content negotiation manager does. + * + * @param webRequest the request + * @return the format, or {@code null} where the request names none + * @since 10.0 + */ + Object requestedFormat(GrailsWebRequest webRequest) { + Object format = webRequest?.params?.get(FORMAT_PARAMETER) + if (!springNegotiation || !format) { + return format + } + String named = format instanceof String[] ? (((String[]) format).length ? ((String[]) format)[0] : null) : + format.toString() + if (!named) { return null } + List types = mediaTypesOf(named) + return types != null && types.every { MediaType type -> type.isWildcardType() } ? null : named + } + + /** + * The MIME types of the {@code Content-Type} of a request, with {@code grails.mime.negotiation.spring}: the type + * Spring reads it as, as the format {@code grails.mime.types} gives it, a type with the {@code +json} or {@code +xml} + * suffix it does not configure as the {@code json} or {@code xml} format, and another type as it is, with no format. + * A request without one is read, as Grails 9 reads it, as of every configured type, so that its format is the first. + * + * @param request the request + * @return the MIME types of its content + * @since 10.0 + */ + MimeType[] resolveContentMimeTypes(HttpServletRequest request) { + String header = request.contentType ?: request.getHeader(HttpHeaders.CONTENT_TYPE) + if (!header) { + return mimeTypes + } + MediaType contentType + try { + contentType = MediaType.parseMediaType(header) + } + catch (InvalidMediaTypeException e) { + LOG.debug('The Content-Type [{}] is not a media type Spring reads: {}', header, e.message) + MimeType unread = new MimeType(header) + unread.name = unread.name?.toLowerCase(Locale.ROOT) + return [unread] as MimeType[] + } + MimeType configured = configuredFor(contentType) + return [configured != null ? withParameters(configured, contentType) : SpringMediaTypeAdapter.toMimeType(contentType)] as MimeType[] + } + + /** + * The media types a Grails format stands for, which Spring MVC's content negotiation manager resolves a request that + * names the format to: its configured types, and for the {@code json} and {@code xml} formats any type with their + * suffix, as Spring MVC's JSON and XML converters write them. + * + * @param format the format + * @return the media types, or {@code null} where no type of the format is configured + * @since 10.0 + */ + List mediaTypesOf(String format) { + List types = [] + for (int i = 0; i < mimeTypes.length; i++) { + if (mimeTypes[i].extension == format && mediaTypes[i] != null && !types.contains(mediaTypes[i])) { + types << mediaTypes[i] + } + } + if (types.isEmpty()) { + return null + } + if (format != null && SUFFIX_FORMATS.contains(format)) { + MediaType suffixed = new MediaType('application', "*+${format}".toString()) + if (!types.contains(suffixed)) { + types << suffixed + } + } + return types + } + /** + * @return the media types of every configured MIME type Spring can read, which a request that names a format no type + * is configured for is not acceptable in + * @since 10.0 + */ + List getConfiguredMediaTypes() { + return mediaTypes.findAll { it }.unique() as List + } + + /** + * @return whether the {@code Accept} header of a request is ignored, as {@code grails.mime.use.accept.header} and + * {@code grails.mime.disable.accept.header.*} say + * @since 10.0 + */ + boolean ignoresAcceptHeader(HttpServletRequest request) { + if (!useAcceptHeader) { + return true + } String userAgent = request.getHeader(HttpHeaders.USER_AGENT) boolean xhr = request.getHeader('X-Requested-With') == 'XMLHttpRequest' - boolean disabledForUserAgent = !(useAcceptHeaderXhr && xhr) && + return !(useAcceptHeaderXhr && xhr) && userAgent != null && disableForUserAgents.any { Pattern pattern -> pattern.matcher(userAgent).find() } - return disabledForUserAgent ? null : request.getHeader(HttpHeaders.ACCEPT) + } + + /** + * Whether a URL mapping handles a request, for which the {@code grails.mime} rules Grails keeps apply to what Spring + * MVC negotiates: the mapping is the request's best matching handler, which each of Spring MVC's handler mappings sets + * for the dispatch it handles, and which a URL mapping takes off the request once its dispatch completes. A web unit + * test sets it for the action it calls. + * + * @param request the request + * @return whether a URL mapping handles it + * @since 10.0 + */ + static boolean handlesRequest(HttpServletRequest request) { + return request.getAttribute(HandlerMapping.BEST_MATCHING_HANDLER_ATTRIBUTE) instanceof UrlMappingInfo + } + + /** + * The strategy that resolves the formats of a request: that of the application's {@code MimeTypesConfiguration}, or, + * in a context without it, such as one a test builds by hand, one built for the request from the application's + * settings. + * + * @param request the request + * @return the strategy + * @since 10.0 + */ + static GrailsContentNegotiationStrategy forRequest(HttpServletRequest request) { + ApplicationContext applicationContext = GrailsWebRequest.lookup()?.applicationContext + if (applicationContext == null && request.servletContext != null) { + applicationContext = WebApplicationContextUtils.getWebApplicationContext(request.servletContext) + } + GrailsContentNegotiationStrategy strategy = applicationContext?.getBeanProvider( + GrailsMimeTypesWebMvcConfigurer + )?.getIfAvailable()?.contentNegotiationStrategy + if (strategy != null) { + return strategy + } + Config config = applicationContext?.getBeanProvider(GrailsApplication)?.getIfAvailable()?.config + MimeUtility mimeUtility = applicationContext?.getBeanProvider(MimeUtility)?.getIfAvailable() + MimeType[] mimeTypes = mimeUtility?.knownMimeTypes as MimeType[] ?: MimeType.createDefaults() + ApplicationContext context = applicationContext + Supplier manager = () -> context?.containsBean(MVC_CONTENT_NEGOTIATION_MANAGER) ? + context.getBean(MVC_CONTENT_NEGOTIATION_MANAGER, ContentNegotiationManager) : null + return new GrailsContentNegotiationStrategy(mimeTypes, config ?: new PropertySourcesConfig(), manager) + } + + /** + * The media types Spring MVC's content negotiation manager resolves for a request, in its order, without the format + * the request names, which Grails resolves on its own, and with its {@code Accept} header ignored where the + * {@code grails.mime} settings ignore it, whether or not a URL mapping handles the request. + * + * @return the media types, or {@code null} where the manager finds the request not acceptable, as for an + * {@code Accept} header Spring cannot read + */ + private List requestedMediaTypes(HttpServletRequest request) { + ContentNegotiationManager manager = contentNegotiationManager?.get() + List strategies = manager != null ? manager.strategies : + [new HeaderContentNegotiationStrategy()] as List + boolean acceptHeaderIgnored = ignoresAcceptHeader(request) + ServletWebRequest webRequest = new ServletWebRequest(request) + try { + for (ContentNegotiationStrategy strategy in strategies) { + if (strategy instanceof GrailsFormatContentNegotiationStrategy || + (acceptHeaderIgnored && strategy instanceof HeaderContentNegotiationStrategy)) { + continue + } + List resolved = strategy.resolveMediaTypes(webRequest) + if (resolved != ContentNegotiationStrategy.MEDIA_TYPE_ALL_LIST) { + return resolved + } + } + } + catch (HttpMediaTypeNotAcceptableException e) { + LOG.debug('The request accepts no format: {}', e.message) + return null + } + return ContentNegotiationStrategy.MEDIA_TYPE_ALL_LIST + } + + /** + * The configured MIME types media types stand for, in the order of the media types, each once, with the parameters, + * such as the quality, of the first that stands for it; and a wildcard no type is configured with the name of, such as + * {@code text/*}, where a configured type is compatible with it, as itself, of the {@code all} format, which + * {@code withFormat} and {@code respond} answer, as Spring MVC answers a wildcard, in the first of their formats that + * has a type compatible with it. + */ + private MimeType[] acceptedMimeTypes(List requested) { + Set listed = Collections.newSetFromMap(new IdentityHashMap()) + Set wildcards = [] + List resolved = [] + for (MediaType mediaType in requested) { + MimeType configured = configuredFor(mediaType) + if (configured != null) { + if (listed.add(configured)) { + resolved << withParameters(configured, mediaType) + } + continue + } + String name = "${mediaType.type}/${mediaType.subtype}" + if (!mediaType.isConcrete() && compatibleWithConfigured(mediaType) && wildcards.add(name)) { + resolved << withParameters(new MimeType(name, ALL_FORMAT), mediaType) + } + } + return resolved as MimeType[] + } + + /** + * Whether a type a request accepts accepts a format: a type of the format; or, of the {@code all} format, the type + * {@code */*}, which accepts any, or a wildcard, such as {@code text/*}, which accepts a format of which a + * configured type is compatible with it. + * + * @param accepted a type {@code response.mimeTypes} resolves + * @param format a format + * @return whether it accepts the format + * @since 10.0 + */ + boolean acceptsFormat(MimeType accepted, String format) { + if (accepted == null) { + return false + } + if (accepted.extension != ALL_FORMAT) { + return accepted.extension == format + } + MediaType wildcard = mediaTypeOf(new MimeType(accepted.name)) + if (wildcard == null || wildcard.isWildcardType()) { + return wildcard != null + } + for (int i = 0; i < mimeTypes.length; i++) { + if (mimeTypes[i].extension == format && mediaTypes[i] != null && wildcard.isCompatibleWith(mediaTypes[i])) { + return true + } + } + return false + } + + /** Whether a configured type that is not itself a wildcard is compatible with a wildcard. */ + private boolean compatibleWithConfigured(MediaType wildcard) { + return mediaTypes.any { MediaType configured -> configured != null && configured.isConcrete() && wildcard.isCompatibleWith(configured) } + } + + /** + * The configured MIME type a media type stands for: the one of its name, of its version where several are; and, for + * a type that is not a wildcard with the {@code +json} or {@code +xml} suffix no type is configured with the name of, + * the own type of the format of that suffix, {@code application/json} or {@code application/xml} where that is + * configured, and otherwise the first type of the format. + * + * @return the type, or {@code null} where no configured type stands for it + */ + private MimeType configuredFor(MediaType mediaType) { + String name = "${mediaType.type}/${mediaType.subtype}" + List named = mimeTypes.findAll { MimeType configured -> configured.name?.equalsIgnoreCase(name) } as List + if (named) { + String version = mediaType.getParameter('v') + return (version ? named.find { MimeType configured -> configured.version == version } : null) ?: named.first() + } + String format = mediaType.isConcrete() ? mediaType.subtypeSuffix?.toLowerCase(Locale.ROOT) : null + if (format != null && SUFFIX_FORMATS.contains(format)) { + String own = "application/${format}" + return mimeTypes.find { MimeType configured -> + configured.extension == format && configured.name?.equalsIgnoreCase(own) + } ?: mimeTypes.find { MimeType configured -> configured.extension == format } + } + return null + } + + /** A configured MIME type with the parameters of the media type it is resolved for, as Grails reads them. */ + private static MimeType withParameters(MimeType configured, MediaType mediaType) { + Map parameters = [:] + mediaType.parameters.each { String name, String value -> parameters.put(name.toLowerCase(Locale.ROOT), value) } + return new MimeType(configured.name, configured.extension, parameters) + } + + /** The media type of a configured MIME type, without the quality Grails gives every MIME type. */ + private static MediaType mediaTypeOf(MimeType mimeType) { + try { + return SpringMediaTypeAdapter.toMediaType(mimeType)?.removeQualityValue() + } + catch (IllegalArgumentException ignored) { + return null + } + } + + private String resolveAcceptHeader(HttpServletRequest request) { + return ignoresAcceptHeader(request) ? null : request.getHeader(HttpHeaders.ACCEPT) } /** diff --git a/grails-mimetypes/src/main/groovy/org/grails/web/mime/GrailsFormatContentNegotiationStrategy.groovy b/grails-mimetypes/src/main/groovy/org/grails/web/mime/GrailsFormatContentNegotiationStrategy.groovy new file mode 100644 index 00000000000..b5e15c878ed --- /dev/null +++ b/grails-mimetypes/src/main/groovy/org/grails/web/mime/GrailsFormatContentNegotiationStrategy.groovy @@ -0,0 +1,74 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.grails.web.mime + +import java.util.function.Supplier + +import groovy.transform.CompileStatic + +import jakarta.servlet.http.HttpServletRequest + +import org.springframework.http.MediaType +import org.springframework.web.HttpMediaTypeNotAcceptableException +import org.springframework.web.accept.ContentNegotiationStrategy +import org.springframework.web.context.request.NativeWebRequest + +import org.grails.web.servlet.mvc.GrailsWebRequest + +/** + * The strategy of Spring MVC's content negotiation manager that resolves the format a request a URL mapping handles + * names, with its {@code format} parameter or a URL extension, to the media types {@code grails.mime.types} gives it, + * ahead of Spring MVC's own strategies, so that what Spring MVC writes for it is in the format Grails resolves for it. It + * leaves any other request, such as one a Spring MVC endpoint handles, to them, and so a request whose format names no + * type, as the {@code all} format does. A request that names a format no type is configured for is not acceptable. + * + * @since 10.0 + */ +@CompileStatic +class GrailsFormatContentNegotiationStrategy implements ContentNegotiationStrategy { + + private final Supplier grailsStrategy + + /** + * @param grailsStrategy supplies the strategy that resolves Grails formats, which Spring MVC's manager is created + * before + */ + GrailsFormatContentNegotiationStrategy(Supplier grailsStrategy) { + this.grailsStrategy = grailsStrategy + } + + @Override + List resolveMediaTypes(NativeWebRequest webRequest) throws HttpMediaTypeNotAcceptableException { + HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest) + if (request == null || !GrailsContentNegotiationStrategy.handlesRequest(request)) { + return MEDIA_TYPE_ALL_LIST + } + GrailsWebRequest grailsRequest = GrailsWebRequest.lookup(request) + GrailsContentNegotiationStrategy strategy = grailsStrategy.get() + Object format = grailsRequest != null ? strategy.requestedFormat(grailsRequest) : null + if (format == null) { + return MEDIA_TYPE_ALL_LIST + } + List mediaTypes = strategy.mediaTypesOf(format.toString()) + if (mediaTypes == null) { + throw new HttpMediaTypeNotAcceptableException(strategy.configuredMediaTypes) + } + return mediaTypes + } +} diff --git a/grails-mimetypes/src/main/groovy/org/grails/web/mime/HttpServletRequestExtension.groovy b/grails-mimetypes/src/main/groovy/org/grails/web/mime/HttpServletRequestExtension.groovy index 8ab811ab03d..3ebde5ca051 100644 --- a/grails-mimetypes/src/main/groovy/org/grails/web/mime/HttpServletRequestExtension.groovy +++ b/grails-mimetypes/src/main/groovy/org/grails/web/mime/HttpServletRequestExtension.groovy @@ -79,7 +79,9 @@ class HttpServletRequestExtension { } /** - * Obtains a list of configured {@link grails.web.mime.MimeType} instances for the request + * Obtains a list of configured {@link grails.web.mime.MimeType} instances for the request: with + * {@code grails.mime.negotiation.spring}, the type of its {@code Content-Type} as Spring reads it, as the format + * {@code grails.mime.types} gives it * * @param request The request * @return A list of configured mime types @@ -87,6 +89,12 @@ class HttpServletRequestExtension { static MimeType[] getMimeTypes(HttpServletRequest request) { MimeType[] result = (MimeType[]) request.getAttribute(GrailsApplicationAttributes.REQUEST_FORMATS) if (!result) { + GrailsContentNegotiationStrategy strategy = GrailsContentNegotiationStrategy.forRequest(request) + if (strategy.springNegotiation) { + result = strategy.resolveContentMimeTypes(request) + request.setAttribute(GrailsApplicationAttributes.REQUEST_FORMATS, result) + return result + } // First try to get context from GrailsWebRequest ApplicationContext context = null GrailsWebRequest webRequest = GrailsWebRequest.lookup() diff --git a/grails-mimetypes/src/main/groovy/org/grails/web/mime/HttpServletResponseExtension.groovy b/grails-mimetypes/src/main/groovy/org/grails/web/mime/HttpServletResponseExtension.groovy index f416c9cabcd..391c6c2aeb3 100755 --- a/grails-mimetypes/src/main/groovy/org/grails/web/mime/HttpServletResponseExtension.groovy +++ b/grails-mimetypes/src/main/groovy/org/grails/web/mime/HttpServletResponseExtension.groovy @@ -24,13 +24,9 @@ import jakarta.servlet.http.HttpServletRequest import jakarta.servlet.http.HttpServletResponse import org.springframework.context.ApplicationContext -import org.springframework.web.context.support.WebApplicationContextUtils -import grails.config.Config -import grails.core.GrailsApplication import grails.web.mime.MimeType import grails.web.mime.MimeUtility -import org.grails.config.PropertySourcesConfig import org.grails.plugins.web.api.MimeTypesApiSupport import org.grails.web.servlet.mvc.GrailsWebRequest import org.grails.web.util.GrailsApplicationAttributes @@ -71,7 +67,13 @@ class HttpServletResponseExtension { final mimeType = getMimeType(response) if (mimeType) { result = mimeType.extension - request.setAttribute(GrailsApplicationAttributes.RESPONSE_FORMAT, result) + // A wildcard such as text/*, which grails.mime.negotiation.spring resolves to a type of the all format, + // is not saved as the format: withFormat and respond answer it with the formats compatible with it, and + // the all format the saved format stands for would answer with any + if (!(mimeType.extension == 'all' && mimeType.name != MimeType.ALL.name && + GrailsContentNegotiationStrategy.forRequest(request).springNegotiation)) { + request.setAttribute(GrailsApplicationAttributes.RESPONSE_FORMAT, result) + } } } return result @@ -93,14 +95,15 @@ class HttpServletResponseExtension { HttpServletRequest request = webRequest.getRequest() MimeType result = (MimeType) request.getAttribute(GrailsApplicationAttributes.RESPONSE_MIME_TYPE) if (!result) { - def formatOverride = webRequest?.params?.format + GrailsContentNegotiationStrategy strategy = GrailsContentNegotiationStrategy.forRequest(request) + def formatOverride = strategy.requestedFormat(webRequest) if (!formatOverride) { formatOverride = request.getAttribute(GrailsApplicationAttributes.RESPONSE_FORMAT) } if (formatOverride) { - def allMimes = getMimeTypes() - MimeType mime = allMimes?.find { MimeType it -> it.extension == formatOverride } - result = mime ? mime : allMimes?.find { it } + // the configured type of the format, or, for a format that is not configured, the first configured + // type, or, with grails.mime.negotiation.spring, none + result = strategy.resolveFormat(formatOverride) // Save the evaluated format as a request attribute. // This is a blatant hack because we should to this @@ -115,7 +118,9 @@ class HttpServletResponseExtension { // - so the saved format is wrong request.setAttribute(GrailsApplicationAttributes.RESPONSE_MIME_TYPE, result) } else { - result = getMimeTypesInternal(request)[0] + // none where the request accepts no configured type, as with grails.mime.negotiation.spring + MimeType[] accepted = getMimeTypesInternal(request) + result = accepted ? accepted[0] : null } } @@ -142,15 +147,17 @@ class HttpServletResponseExtension { GrailsWebRequest webRequest = GrailsWebRequest.lookup() HttpServletRequest request = webRequest.getRequest() MimeType[] result = (MimeType[]) request.getAttribute(GrailsApplicationAttributes.RESPONSE_MIME_TYPES) - if (!result) { - def formatOverride = webRequest?.params?.format + if (result == null) { + GrailsContentNegotiationStrategy strategy = GrailsContentNegotiationStrategy.forRequest(request) + def formatOverride = strategy.requestedFormat(webRequest) if (!formatOverride) { formatOverride = request.getAttribute(GrailsApplicationAttributes.RESPONSE_FORMAT) } if (formatOverride) { - def allMimes = getMimeTypes() - MimeType mime = allMimes.find { MimeType it -> it.extension == formatOverride } - result = [ mime ? mime : getMimeTypes()[0] ] as MimeType[] + // with grails.mime.negotiation.spring, none for a format that is not configured, which the request + // accepts no configured type in + MimeType mime = strategy.resolveFormat(formatOverride) + result = mime != null ? [mime] as MimeType[] : new MimeType[0] // Save the evaluated format as a request attribute. // This is a blatant hack because we should to this @@ -185,21 +192,8 @@ class HttpServletResponseExtension { private static MimeType[] getMimeTypesInternal(HttpServletRequest request) { MimeType[] result = (MimeType[]) request.getAttribute(GrailsApplicationAttributes.RESPONSE_FORMATS) - if (!result) { - ApplicationContext applicationContext = GrailsWebRequest.lookup()?.applicationContext - if (applicationContext == null && request.servletContext != null) { - applicationContext = WebApplicationContextUtils.getWebApplicationContext(request.servletContext) - } - GrailsContentNegotiationStrategy strategy = applicationContext?.getBeanProvider( - GrailsMimeTypesWebMvcConfigurer - )?.getIfAvailable()?.contentNegotiationStrategy - if (strategy == null) { - // A context without MimeTypesConfiguration, such as one a test builds by hand, has no - // configurer: the strategy is built for the request from the application's settings - Config config = applicationContext?.getBeanProvider(GrailsApplication)?.getIfAvailable()?.config - strategy = new GrailsContentNegotiationStrategy(getMimeTypes(), config ?: new PropertySourcesConfig()) - } - result = strategy.resolveAcceptedMimeTypes(request) + if (result == null) { + result = GrailsContentNegotiationStrategy.forRequest(request).resolveAcceptedMimeTypes(request) request.setAttribute(GrailsApplicationAttributes.RESPONSE_FORMATS, result) } return result diff --git a/grails-mimetypes/src/test/groovy/org/grails/plugins/web/mime/MimeTypesConfigurationSpec.groovy b/grails-mimetypes/src/test/groovy/org/grails/plugins/web/mime/MimeTypesConfigurationSpec.groovy index 0f4850d6782..3f757c8b055 100644 --- a/grails-mimetypes/src/test/groovy/org/grails/plugins/web/mime/MimeTypesConfigurationSpec.groovy +++ b/grails-mimetypes/src/test/groovy/org/grails/plugins/web/mime/MimeTypesConfigurationSpec.groovy @@ -125,7 +125,7 @@ class MimeTypesConfigurationSpec extends Specification { def mimeUtility = Stub(ObjectProvider) { getObject() >> new DefaultMimeUtility(custom) } expect: - MimeTypesConfiguration.grailsMimeTypesWebMvcConfigurer(mimeUtility, new DefaultGrailsApplication()) + MimeTypesConfiguration.grailsMimeTypesWebMvcConfigurer(mimeUtility, new DefaultGrailsApplication(), Stub(ObjectProvider)) .contentNegotiationStrategy.configuredMimeTypes as List == custom as List } diff --git a/grails-mimetypes/src/test/groovy/org/grails/web/mime/SpringFormatNegotiationSpec.groovy b/grails-mimetypes/src/test/groovy/org/grails/web/mime/SpringFormatNegotiationSpec.groovy new file mode 100644 index 00000000000..11915007f54 --- /dev/null +++ b/grails-mimetypes/src/test/groovy/org/grails/web/mime/SpringFormatNegotiationSpec.groovy @@ -0,0 +1,459 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.grails.web.mime + +import org.springframework.context.ApplicationContext +import org.springframework.context.annotation.Bean +import org.springframework.context.annotation.Configuration +import org.springframework.context.annotation.Import +import org.springframework.core.env.ConfigurableEnvironment +import org.springframework.core.env.MapPropertySource +import org.springframework.http.MediaType +import org.springframework.mock.web.MockHttpServletRequest +import org.springframework.mock.web.MockHttpServletResponse +import org.springframework.mock.web.MockServletContext +import org.springframework.web.HttpMediaTypeNotAcceptableException +import org.springframework.web.accept.ContentNegotiationManager +import org.springframework.web.accept.ContentNegotiationStrategy +import org.springframework.web.accept.HeaderContentNegotiationStrategy +import org.springframework.web.accept.ParameterContentNegotiationStrategy +import org.springframework.web.context.request.RequestContextHolder +import org.springframework.web.context.request.ServletWebRequest +import org.springframework.web.context.support.AnnotationConfigWebApplicationContext +import org.springframework.web.method.HandlerMethod +import org.springframework.web.servlet.HandlerMapping +import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer +import org.springframework.web.servlet.config.annotation.EnableWebMvc +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer + +import grails.config.Settings +import grails.core.DefaultGrailsApplication +import grails.core.GrailsApplication +import grails.util.GrailsWebMockUtil +import grails.web.mapping.UrlMappingInfo +import org.grails.config.PropertySourcesConfig +import org.grails.plugins.web.mime.MimeTypesConfiguration +import org.grails.web.servlet.mvc.GrailsWebRequest +import org.grails.web.util.GrailsApplicationAttributes +import spock.lang.AutoCleanup +import spock.lang.Specification + +/** + * With {@code grails.mime.negotiation.spring}, Grails formats are resolved with Spring MVC's content negotiation manager, + * as the formats {@code grails.mime.types} gives the media types it resolves, and the manager applies the + * {@code grails.mime} rules Grails keeps to the requests a URL mapping handles. + */ +class SpringFormatNegotiationSpec extends Specification { + + @AutoCleanup + AnnotationConfigWebApplicationContext context + + void cleanup() { + RequestContextHolder.resetRequestAttributes() + } + + void "without the setting, Spring MVC's manager is left as it is"() { + when: + start([:]) + + then: + manager().getClass() == ContentNegotiationManager + } + + void "with the setting, Spring MVC's manager resolves a Grails format ahead of its own strategies, and keeps its formats"() { + when: + start((Settings.MIME_NEGOTIATION_SPRING): true) + def manager = manager() + + then: 'the format strategy goes first, and the Accept header is still read by a header strategy' + manager instanceof GrailsContentNegotiationManager + manager.strategies.first() instanceof GrailsFormatContentNegotiationStrategy + manager.getStrategy(HeaderContentNegotiationStrategy) instanceof GrailsAcceptHeaderContentNegotiationStrategy + + and: 'the formats Grails registers with Spring MVC are those of its manager' + manager.mediaTypeMappings['hal'] == MediaType.parseMediaType('application/hal+json') + manager.resolveFileExtensions(MediaType.APPLICATION_JSON) == ['json'] + manager.mediaTypeMappings == ((GrailsContentNegotiationManager) manager).springManager.mediaTypeMappings + + and: 'it is the one content negotiation strategy bean, which Spring Security adopts' + context.getBeansOfType(ContentNegotiationStrategy).keySet() == [GrailsContentNegotiationStrategy.MVC_CONTENT_NEGOTIATION_MANAGER] as Set + } + + void 'the format a request names decides what Spring MVC writes for it only while a URL mapping handles it: #handled'() { + given: + start((Settings.MIME_NEGOTIATION_SPRING): true) + def request = request('Accept': 'application/json') + handledBy(request, handler) + GrailsWebRequest.lookup().params.format = 'xml' + + expect: + manager().resolveMediaTypes(new ServletWebRequest(request)) == resolved + + where: + handled | handler || resolved + 'a URL mapping' | urlMapping() || ['text/xml', 'application/xml', 'application/*+xml'].collect { MediaType.parseMediaType(it) } + 'a Spring MVC endpoint' | endpoint() || [MediaType.APPLICATION_JSON] + 'a filter, before any handler' | null || [MediaType.APPLICATION_JSON] + 'a filter, after a controller dispatch ended' | 'controller' || [MediaType.APPLICATION_JSON] + } + + void 'a request a URL mapping handles that names a format no type is configured for is not acceptable to Spring MVC'() { + given: + start((Settings.MIME_NEGOTIATION_SPRING): true) + def request = request('Accept': 'application/json') + handledBy(request, urlMapping()) + GrailsWebRequest.lookup().params.format = 'unknown' + + when: + manager().resolveMediaTypes(new ServletWebRequest(request)) + + then: + HttpMediaTypeNotAcceptableException e = thrown() + e.supportedMediaTypes.contains(MediaType.APPLICATION_JSON) + + and: 'Grails resolves no format for it' + GrailsWebRequest.lookup().currentResponse.format == null + GrailsWebRequest.lookup().currentResponse.mimeType == null + } + + void 'the all format names no type, so the Accept header decides, for Spring MVC and for Grails'() { + given: + start((Settings.MIME_NEGOTIATION_SPRING): true) + def request = request('Accept': 'application/json') + handledBy(request, urlMapping()) + GrailsWebRequest.lookup().params.format = 'all' + + expect: + manager().resolveMediaTypes(new ServletWebRequest(request)) == [MediaType.APPLICATION_JSON] + GrailsWebRequest.lookup().currentResponse.format == 'json' + } + + void 'the first value of the format parameter is the format, as Spring MVC reads its parameter'() { + given: + start((Settings.MIME_NEGOTIATION_SPRING): true) + def request = request([:]) + request.addParameter('format', 'xml', 'json') + handledBy(request, urlMapping()) + + expect: + GrailsWebRequest.lookup().currentResponse.format == 'xml' + manager().resolveMediaTypes(new ServletWebRequest(request)).first() == MediaType.TEXT_XML + } + + void 'the Accept header of a user agent the settings ignore it for is ignored by Spring MVC for a #handled request only'() { + given: + start((Settings.MIME_NEGOTIATION_SPRING): true, (Settings.MIME_DISABLE_ACCEPT_HEADER_FOR_USER_AGENTS): ['Gecko']) + def request = request('Accept': 'application/json', 'User-Agent': 'Mozilla/5.0 Gecko/20100101') + handledBy(request, handler) + + expect: + manager().resolveMediaTypes(new ServletWebRequest(request)) == resolved + GrailsWebRequest.lookup().currentResponse.format == 'all' + + where: + handled | handler || resolved + 'URL mapping' | urlMapping() || ContentNegotiationStrategy.MEDIA_TYPE_ALL_LIST + 'Spring MVC endpoint' | endpoint() || [MediaType.APPLICATION_JSON] + } + + void 'an XHR request keeps its Accept header unless the settings ignore it for XHR requests too'() { + given: + start((Settings.MIME_NEGOTIATION_SPRING): true, (Settings.MIME_DISABLE_ACCEPT_HEADER_FOR_USER_AGENTS): ['Gecko'], + (Settings.MIME_DISABLE_ACCEPT_HEADER_FOR_USER_AGENTS_XHR): xhrToo) + def request = request('Accept': 'application/json', 'User-Agent': 'Gecko', 'X-Requested-With': 'XMLHttpRequest') + handledBy(request, urlMapping()) + + expect: + manager().resolveMediaTypes(new ServletWebRequest(request)) == resolved + GrailsWebRequest.lookup().currentResponse.format == format + + where: + xhrToo || resolved | format + false || [MediaType.APPLICATION_JSON] | 'json' + true || ContentNegotiationStrategy.MEDIA_TYPE_ALL_LIST | 'all' + } + + void 'grails.mime.use.accept.header: false ignores the Accept header of a request a URL mapping handles'() { + given: + start((Settings.MIME_NEGOTIATION_SPRING): true, (Settings.MIME_USE_ACCEPT_HEADER): false) + def request = request('Accept': 'application/json') + handledBy(request, urlMapping()) + + expect: + manager().resolveMediaTypes(new ServletWebRequest(request)) == ContentNegotiationStrategy.MEDIA_TYPE_ALL_LIST + GrailsWebRequest.lookup().currentResponse.format == 'all' + } + + void 'the Accept header #accept resolves to the formats #formats, in the order Spring MVC resolves its types in'() { + given: + start((Settings.MIME_NEGOTIATION_SPRING): true) + request('Accept': accept) + + expect: + GrailsWebRequest.lookup().currentResponse.mimeTypes*.extension == formats + GrailsWebRequest.lookup().currentResponse.format == formats[0] + + where: + accept || formats + '*/*' || ['all'] + '*/*, application/json' || ['json', 'all'] + 'application/json;q=0.5, application/xml' || ['xml', 'json'] + 'text/html;q=0.9, application/json;q=0.9' || ['html', 'json'] + 'text/*' || ['all'] + 'application/*+json' || ['all'] + 'image/*' || [] + 'application/problem+json' || ['json'] + 'application/vnd.api+json, application/xml' || ['json', 'xml'] + 'application/soap+xml' || ['xml'] + 'application/xml, application/atom+xml' || ['xml', 'atom'] + 'text/xml;q=0.5, application/xml;q=0.9, application/json' || ['json', 'xml', 'xml'] + 'image/png' || [] + 'application/json;q=abc' || [] + } + + void 'a configured type of the Accept header keeps its parameters, the quality among them'() { + given: + start((Settings.MIME_NEGOTIATION_SPRING): true) + request('Accept': 'application/json;q=0.8;profile=compact') + + expect: + with(GrailsWebRequest.lookup().currentResponse.mimeTypes.first()) { + name == 'application/json' + extension == 'json' + parameters == [q: '0.8', profile: 'compact'] + } + } + + void 'a client that accepts any type is of the all format, also where it is not configured'() { + given: + start((Settings.MIME_NEGOTIATION_SPRING): true, 'grails.mime.types': [json: 'application/json', html: 'text/html']) + request('Accept': '*/*') + + expect: + with(GrailsWebRequest.lookup().currentResponse.mimeTypes.toList()) { + it*.name == ['*/*'] + it*.extension == ['all'] + } + GrailsWebRequest.lookup().currentResponse.withFormat { + html { 'html' } + json { 'json' } + } == 'html' + } + + void 'a wildcard is of the all format, which withFormat answers with the first block compatible with it: #result for #accept'() { + given: + start((Settings.MIME_NEGOTIATION_SPRING): true) + request('Accept': accept) + + expect: + GrailsWebRequest.lookup().currentResponse.mimeTypes*.name == [accept] + GrailsWebRequest.lookup().currentResponse.format == 'all' + GrailsWebRequest.lookup().currentResponse.withFormat { + pdf { 'pdf' } + json { 'json' } + html { 'html' } + } == result + + where: + accept || result + 'text/*' || 'json' + 'application/*+xml' || 'html' + 'application/*' || 'pdf' + } + + void 'a wildcard no block is compatible with leaves withFormat to the next type the request accepts'() { + given: + start((Settings.MIME_NEGOTIATION_SPRING): true) + request('Accept': 'text/*, application/pdf;q=0.5') + + expect: + GrailsWebRequest.lookup().currentResponse.format == 'all' + GrailsWebRequest.lookup().currentResponse.withFormat { + pdf { 'pdf' } + } == 'pdf' + } + + void 'withFormat runs the block of the first format the request accepts that has one: #result for #accept'() { + given: + start((Settings.MIME_NEGOTIATION_SPRING): true) + request('Accept': accept) + + expect: + GrailsWebRequest.lookup().currentResponse.withFormat { + json { 'json' } + text { 'text' } + html { 'html' } + } == result + + where: + accept || result + 'application/xml, */*, text/html' || 'html' + 'application/xml, text/csv, */*' || 'json' + 'application/xml, text/csv' || null + 'image/png' || null + } + + void "withFormat runs its * block for a request that accepts no configured type"() { + given: + start((Settings.MIME_NEGOTIATION_SPRING): true) + request('Accept': 'image/png') + + expect: + GrailsWebRequest.lookup().currentResponse.withFormat { + json { 'json' } + '*' { 'any' } + } == 'any' + } + + void "Spring MVC's parameter negotiation, which the application enables, resolves Grails formats too"() { + given: 'parameter negotiation with a parameter of its own name, as spring.mvc.contentnegotiation.* enables it' + start((Settings.MIME_NEGOTIATION_SPRING): true, (ParameterConfiguration.ENABLED): true) + def request = request('Accept': 'application/json') + request.addParameter('mediaType', 'xml') + + expect: + manager().getStrategy(ParameterContentNegotiationStrategy) != null + GrailsWebRequest.lookup().currentResponse.format == 'xml' + } + + void 'the Content-Type #contentType is the request format #format'() { + given: + start((Settings.MIME_NEGOTIATION_SPRING): true) + def request = request([:]) + if (contentType) { + request.contentType = contentType + } + + expect: + request.format == format + + where: + contentType || format + null || 'all' + 'application/json;charset=UTF-8' || 'json' + 'APPLICATION/JSON' || 'json' + 'text/xml' || 'xml' + 'application/hal+json' || 'hal' + 'application/vnd.acme+json' || 'json' + 'application/problem+xml' || 'xml' + 'application/x-www-form-urlencoded' || 'form' + 'image/png' || null + 'application/json;charset=' || null + } + + void 'a Content-Type keeps its parameters, and one no type is configured for is the type itself, in lower case'() { + given: + start((Settings.MIME_NEGOTIATION_SPRING): true) + def request = request([:]) + + when: + request.contentType = 'application/json;charset=UTF-8' + + then: + request.mimeTypes*.name == ['application/json'] + request.mimeTypes[0].parameters.charset == 'UTF-8' + + when: + request.removeAttribute(GrailsApplicationAttributes.REQUEST_FORMATS) + request.contentType = 'Image/PNG' + + then: + request.mimeTypes*.name == ['image/png'] + } + + void 'without the setting, the Grails 9 rules resolve the formats'() { + given: + start([:]) + request('Accept': '*/*, application/json') + + expect: + GrailsWebRequest.lookup().currentResponse.format == 'all' + } + + private void start(Map properties) { + context = new AnnotationConfigWebApplicationContext() + context.servletContext = new MockServletContext() + context.environment.propertySources.addFirst(new MapPropertySource('test', properties)) + context.register(NegotiationConfiguration) + context.refresh() + } + + private ContentNegotiationManager manager() { + context.getBean(GrailsContentNegotiationStrategy.MVC_CONTENT_NEGOTIATION_MANAGER, ContentNegotiationManager) + } + + private MockHttpServletRequest request(Map headers) { + def request = new MockHttpServletRequest(context.servletContext) + headers.each { String name, String value -> request.addHeader(name, value) } + GrailsWebMockUtil.bindMockWebRequest(context, request, new MockHttpServletResponse()) + request + } + + private static void handledBy(MockHttpServletRequest request, Object handler) { + if (handler == 'controller') { + request.setAttribute(GrailsApplicationAttributes.CONTROLLER, new Object()) + } + else if (handler != null) { + request.setAttribute(HandlerMapping.BEST_MATCHING_HANDLER_ATTRIBUTE, handler) + } + } + + private UrlMappingInfo urlMapping() { + Stub(UrlMappingInfo) + } + + private static HandlerMethod endpoint() { + new HandlerMethod(new Object(), Object.getMethod('toString')) + } + + @Configuration(proxyBeanMethods = false) + @EnableWebMvc + @Import([MimeTypesConfiguration, ParameterConfiguration]) + static class NegotiationConfiguration { + + @Bean + GrailsApplication grailsApplication(ApplicationContext applicationContext, ConfigurableEnvironment environment) { + def application = new DefaultGrailsApplication() + application.config = new PropertySourcesConfig(environment.propertySources) + application.applicationContext = applicationContext + application.mainContext = applicationContext + application + } + } + + /** Enables Spring MVC's parameter negotiation, as {@code spring.mvc.contentnegotiation.*} does, where the test says. */ + @Configuration(proxyBeanMethods = false) + static class ParameterConfiguration implements WebMvcConfigurer { + + static final String ENABLED = 'test.parameter.negotiation' + + private final boolean enabled + + ParameterConfiguration(ConfigurableEnvironment environment) { + enabled = environment.getProperty(ENABLED, Boolean, false) + } + + @Override + void configureContentNegotiation(ContentNegotiationConfigurer configurer) { + if (enabled) { + configurer.favorParameter(true).parameterName('mediaType') + } + } + } +} diff --git a/grails-mimetypes/src/test/groovy/org/grails/web/servlet/mvc/RequestAndResponseMimeTypesApiSpec.groovy b/grails-mimetypes/src/test/groovy/org/grails/web/servlet/mvc/RequestAndResponseMimeTypesApiSpec.groovy index 83e21580f58..9534626371a 100644 --- a/grails-mimetypes/src/test/groovy/org/grails/web/servlet/mvc/RequestAndResponseMimeTypesApiSpec.groovy +++ b/grails-mimetypes/src/test/groovy/org/grails/web/servlet/mvc/RequestAndResponseMimeTypesApiSpec.groovy @@ -226,7 +226,7 @@ class RequestAndResponseMimeTypesApiSpec extends Specification{ def context = (GenericWebApplicationContext) webRequest.applicationContext def own = new DefaultMimeUtility((buildMimeTypes() + new MimeType('application/vnd.own+json', 'own')) as MimeType[]) def configurer = Spy(MimeTypesConfiguration.grailsMimeTypesWebMvcConfigurer( - Stub(ObjectProvider) { getObject() >> own }, (GrailsApplication) application)) + Stub(ObjectProvider) { getObject() >> own }, (GrailsApplication) application, Stub(ObjectProvider))) context.beanFactory.registerSingleton('grailsMimeTypesWebMvcConfigurer', configurer) webRequest.currentRequest.addHeader('Accept', accept) @@ -337,6 +337,23 @@ class RequestAndResponseMimeTypesApiSpec extends Specification{ } + void "the response type is that of the block withFormat runs for a client that accepts any type"() { + given: + final webRequest = boundMimeTypeRequest() + webRequest.currentRequest.addHeader('Accept', '*/*') + + when: + def result = webRequest.currentResponse.withFormat { + xml { 'got xml' } + html { 'got html' } + } + + then: 'as a view is looked up for it afterwards' + result == 'got xml' + webRequest.currentResponse.format == 'xml' + webRequest.currentResponse.mimeType.extension == 'xml' + } + @Issue("GRAILS-10973") void "request.withFormat should choose wildcard choice when format == all"() { when: @@ -464,7 +481,7 @@ class RequestAndResponseMimeTypesApiSpec extends Specification{ webRequest.currentRequest.addHeader('User-Agent', 'Trident/7.0') expect: 'the configurer is created, and the other entry is found' - MimeTypesConfiguration.grailsMimeTypesWebMvcConfigurer(Stub(ObjectProvider), (GrailsApplication) application) + MimeTypesConfiguration.grailsMimeTypesWebMvcConfigurer(Stub(ObjectProvider), (GrailsApplication) application, Stub(ObjectProvider)) webRequest.currentResponse.withFormat { json { 'got json' } html { 'got html' } @@ -478,7 +495,7 @@ class RequestAndResponseMimeTypesApiSpec extends Specification{ application.setConfig(config) when: 'the configurer an application has is created' - MimeTypesConfiguration.grailsMimeTypesWebMvcConfigurer(Stub(ObjectProvider), (GrailsApplication) application) + MimeTypesConfiguration.grailsMimeTypesWebMvcConfigurer(Stub(ObjectProvider), (GrailsApplication) application, Stub(ObjectProvider)) then: IllegalArgumentException e = thrown() diff --git a/grails-rest-transforms/src/main/groovy/grails/artefact/controller/RestResponder.groovy b/grails-rest-transforms/src/main/groovy/grails/artefact/controller/RestResponder.groovy index 8a0a983716b..0cd6cfb0bd7 100644 --- a/grails-rest-transforms/src/main/groovy/grails/artefact/controller/RestResponder.groovy +++ b/grails-rest-transforms/src/main/groovy/grails/artefact/controller/RestResponder.groovy @@ -30,6 +30,7 @@ import org.springframework.beans.factory.annotation.Autowired import org.springframework.context.ApplicationContext import org.springframework.context.i18n.LocaleContextHolder import org.springframework.http.HttpStatus +import org.springframework.http.InvalidMediaTypeException import org.springframework.http.MediaType import org.springframework.http.ProblemDetail import org.springframework.validation.BeanPropertyBindingResult @@ -50,6 +51,7 @@ import org.grails.plugins.web.rest.render.SelectiveRenderer import org.grails.plugins.web.rest.render.ServletRenderContext import org.grails.plugins.web.rest.render.html.DefaultHtmlRenderer import org.grails.web.gsp.io.GrailsConventionGroovyPageLocator +import org.grails.web.mime.GrailsContentNegotiationStrategy import org.grails.web.servlet.mvc.GrailsWebRequest import org.grails.web.util.GrailsApplicationAttributes @@ -169,6 +171,8 @@ trait RestResponder { List formats = calculateFormats(webRequest.actionName, value, args) final response = webRequest.getCurrentResponse() MimeType[] mimeTypes = getResponseFormat(response) + // with grails.mime.negotiation.spring, a wildcard such as text/* is a type of the all format too + boolean springNegotiation = GrailsContentNegotiationStrategy.forRequest(webRequest.currentRequest).springNegotiation def registry = rendererRegistry if (registry == null) { // a controller Spring did not create, such as one a test creates with new, responds with the registry an @@ -209,7 +213,9 @@ trait RestResponder { } // The response is in the first type the client accepts, in its order, that the action responds in and a renderer - // renders the value in; a client that accepts any type is answered in the first of the action's formats that is + // renders the value in; a client that accepts any type is answered in the first of the action's formats that is, + // and one that accepts a wildcard such as text/*, which grails.mime.negotiation.spring resolves to a type of the + // all format, in the first of them with a type compatible with it, as Spring MVC answers it MimeType matched = null boolean negotiating = true while (negotiating) { @@ -217,10 +223,11 @@ trait RestResponder { negotiation: for (MimeType accepted in mimeTypes) { List candidates = [accepted] - if (accepted == MimeType.ALL && formats) { + if ((accepted == MimeType.ALL || (springNegotiation && accepted.extension == 'all')) && formats) { final allMimeTypes = MimeType.getConfiguredMimeTypes() - candidates = formats.collect { String format -> allMimeTypes.find { MimeType mt -> mt.extension == format } } - .findAll { MimeType mt -> mt != null } + candidates = formats.collect { String format -> + allMimeTypes.find { MimeType mt -> mt.extension == format && compatible(accepted, mt) } + }.findAll { MimeType mt -> mt != null } } for (MimeType mimeType in candidates) { if (!formats.contains(mimeType.extension)) { @@ -332,6 +339,22 @@ trait RestResponder { callRender([status: statusCode ?: HttpStatus.NOT_ACCEPTABLE.value() ]) } + /** + * Whether a configured type is compatible with a type of the {@code all} format a client accepts: any is with + * {@code */*}, and a wildcard such as {@code text/*} is with the types Spring MVC finds compatible with it. + */ + private static boolean compatible(MimeType accepted, MimeType configured) { + if (accepted.name == MimeType.ALL.name) { + return true + } + try { + return MediaType.parseMediaType(accepted.name).isCompatibleWith(MediaType.parseMediaType(configured.name)) + } + catch (InvalidMediaTypeException ignored) { + return false + } + } + /** * Whether a renderer renders a value: one that renders some values only, such as that of markup views without a * renderer of XML, says so, as a Spring message converter says whether it writes a value. diff --git a/grails-test-suite-web/src/test/groovy/grails/config/MigrationSettingsMetadataSpec.groovy b/grails-test-suite-web/src/test/groovy/grails/config/MigrationSettingsMetadataSpec.groovy index ea39cabb6ef..3aca9f92f83 100644 --- a/grails-test-suite-web/src/test/groovy/grails/config/MigrationSettingsMetadataSpec.groovy +++ b/grails-test-suite-web/src/test/groovy/grails/config/MigrationSettingsMetadataSpec.groovy @@ -39,6 +39,7 @@ class MigrationSettingsMetadataSpec extends Specification { Settings.DATABINDING_JSON_JACKSON | Settings.DATABINDING_JSON_JACKSON_DEFAULT Settings.SETTING_EXCEPTION_RESOLVER_SPRING_HANDLERS | Settings.SETTING_EXCEPTION_RESOLVER_SPRING_HANDLERS_DEFAULT Settings.CONTROLLERS_RESPONSE_BODY | Settings.CONTROLLERS_RESPONSE_BODY_DEFAULT + Settings.MIME_NEGOTIATION_SPRING | Settings.MIME_NEGOTIATION_SPRING_DEFAULT } private static Map metadataDefaults() { diff --git a/grails-test-suite-web/src/test/groovy/grails/rest/web/SpringFormatNegotiationRespondSpec.groovy b/grails-test-suite-web/src/test/groovy/grails/rest/web/SpringFormatNegotiationRespondSpec.groovy new file mode 100644 index 00000000000..5a4195e05af --- /dev/null +++ b/grails-test-suite-web/src/test/groovy/grails/rest/web/SpringFormatNegotiationRespondSpec.groovy @@ -0,0 +1,234 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package grails.rest.web + +import org.springframework.http.HttpStatus +import org.springframework.http.MediaType +import org.springframework.http.ProblemDetail +import org.springframework.web.accept.ContentNegotiationManager +import org.springframework.web.context.request.ServletWebRequest + +import grails.artefact.Artefact +import grails.config.Settings +import grails.testing.web.controllers.ControllerUnitTest +import grails.validation.Validateable +import org.grails.web.mime.GrailsContentNegotiationManager +import spock.lang.Specification + +/** + * With {@code grails.mime.negotiation.spring}, {@code respond} answers in the format Spring MVC's content negotiation + * resolves for the request, and a request that accepts none of the action's formats is not acceptable. + */ +class SpringFormatNegotiationRespondSpec extends Specification implements ControllerUnitTest { + + Closure doWithConfig() { + { config -> + config[Settings.WEB_RENDERING_JSON_SPRING] = true + config[Settings.MIME_NEGOTIATION_SPRING] = true + } + } + + void "a web unit test negotiates with the manager Spring MVC negotiates with in an application"() { + expect: + applicationContext.getBean('mvcContentNegotiationManager', ContentNegotiationManager) instanceof GrailsContentNegotiationManager + } + + void 'what Spring MVC writes for an action of a web unit test is negotiated with the format the request names, as in an application'() { + given: + request.addHeader('Accept', 'application/json') + params.format = 'xml' + + when: 'the test calls the action of the controller' + controller + + then: + applicationContext.getBean('mvcContentNegotiationManager', ContentNegotiationManager) + .resolveMediaTypes(new ServletWebRequest(request)).first() == MediaType.TEXT_XML + } + + void 'a body of a type with the +json suffix is bound as JSON'() { + given: + request.method = 'POST' + request.contentType = 'application/merge-patch+json' + request.content = '{"title":"Grails"}'.bytes + + when: + def model = controller.save() + + then: + request.format == 'json' + model.title == 'Grails' + } + + void 'a client that accepts #accept is answered in #format by an action that responds in XML and JSON'() { + given: + request.addHeader('Accept', accept) + + when: + controller.respond([title: 'Grails'], formats: ['xml', 'json']) + + then: + response.status == 200 + response.contentType.contains(format) + + where: + accept || format + '*/*, application/json' || 'json' + 'application/*+json' || 'json' + 'text/*' || 'xml' + 'application/merge-patch+json' || 'json' + 'application/soap+xml' || 'xml' + } + + void 'a client that accepts no format of the action is not acceptable, as to Spring MVC'() { + given: + request.addHeader('Accept', accept) + + when: + controller.respond([title: 'Grails'], formats: ['json']) + + then: + response.status == 406 + + where: + accept << ['image/png', 'image/*', 'application/json;q=2'] + } + + void 'a request that names a format no type is configured for is not acceptable'() { + given: + request.addHeader('Accept', 'application/json') + params.format = 'unknown' + + when: + controller.respond([title: 'Grails'], formats: ['json']) + + then: + response.status == 406 + } + + void 'the all format names no type, so the Accept header decides'() { + given: + request.addHeader('Accept', 'application/json') + params.format = 'all' + + when: + controller.respond([title: 'Grails'], formats: ['xml', 'json']) + + then: + response.contentType.startsWith('application/json') + response.json == [title: 'Grails'] + } + + void 'a problem for a client whose Accept header Spring MVC cannot read is answered with its status alone, as Spring MVC answers it'() { + given: + request.addHeader('Accept', 'application/json;q=2') + + when: + controller.respond(ProblemDetail.forStatus(HttpStatus.CONFLICT), formats: ['json']) + + then: + response.status == 409 + response.contentAsString == '' + } +} + +/** + * Without {@code grails.mime.negotiation.spring}, the Grails 9 rules resolve the format {@code respond} answers in. + */ +class GrailsFormatNegotiationRespondSpec extends Specification implements ControllerUnitTest { + + Closure doWithConfig() { + { config -> config[Settings.WEB_RENDERING_JSON_SPRING] = true } + } + + void "Spring MVC's manager is left as it is"() { + expect: + applicationContext.getBean('mvcContentNegotiationManager', ContentNegotiationManager).getClass() == ContentNegotiationManager + } + + void 'a client that accepts #accept is answered in #format, as in Grails 9'() { + given: + request.addHeader('Accept', accept) + + when: + controller.respond([title: 'Grails'], formats: ['xml', 'json']) + + then: + response.status == 200 + response.contentType.contains(format) + + where: + accept || format + '*/*, application/json' || 'xml' + 'application/*+json' || 'xml' + 'application/merge-patch+json' || 'xml' + 'image/png' || 'xml' + } + + void 'a body of a type with the +json suffix is of no format, and not bound'() { + given: + request.method = 'POST' + request.contentType = 'application/merge-patch+json' + request.content = '{"title":"Grails"}'.bytes + + when: + def model = controller.save() + + then: + request.format == null + model.title == null + } + + void 'a client that accepts any type of a version is answered 406, as in Grails 9'() { + given: + request.addHeader('Accept', '*/*;v=2') + + when: + controller.respond([title: 'Grails'], formats: ['json']) + + then: + response.status == 406 + } + + void 'a request that names a format no type is configured for is answered in the first configured type'() { + given: + request.addHeader('Accept', 'application/json') + params.format = 'unknown' + + when: + controller.respond([title: 'Grails'], formats: ['xml', 'json']) + + then: 'the first configured type is the all format, which the first format of the action answers' + response.status == 200 + response.contentType.contains('xml') + } +} + +@Artefact('Controller') +class NegotiatedResponseController { + + def save(NegotiatedCommand command) { + [title: command.title] + } +} + +class NegotiatedCommand implements Validateable { + + String title +} diff --git a/grails-testing-support-web/src/main/groovy/grails/testing/web/GrailsWebUnitTest.groovy b/grails-testing-support-web/src/main/groovy/grails/testing/web/GrailsWebUnitTest.groovy index 678d3b85f26..a66b100fd89 100644 --- a/grails-testing-support-web/src/main/groovy/grails/testing/web/GrailsWebUnitTest.groovy +++ b/grails-testing-support-web/src/main/groovy/grails/testing/web/GrailsWebUnitTest.groovy @@ -24,6 +24,7 @@ import groovy.transform.CompileStatic import org.springframework.mock.web.MockHttpSession import org.springframework.mock.web.MockServletContext +import org.springframework.web.servlet.HandlerMapping import grails.artefact.Controller import grails.artefact.TagLibrary @@ -44,6 +45,7 @@ import org.grails.plugins.testing.GrailsMockHttpServletRequest import org.grails.plugins.testing.GrailsMockHttpServletResponse import org.grails.taglib.TagLibraryLookup import org.grails.taglib.TagLibraryMetaUtils +import org.grails.web.mapping.ForwardUrlMappingInfo import org.grails.testing.GrailsUnitTest import org.grails.web.servlet.mvc.GrailsWebRequest import org.grails.web.util.GrailsApplicationAttributes @@ -148,6 +150,10 @@ trait GrailsWebUnitTest implements GrailsUnitTest { webRequest.request.setAttribute(GrailsApplicationAttributes.CONTROLLER, controller) webRequest.controllerName = GrailsNameUtils.getLogicalPropertyName(controller.class.name, ControllerArtefactHandler.TYPE) + // A URL mapping handles the request, as in an application, so that what Spring MVC writes for the action is + // negotiated as there + webRequest.request.setAttribute(HandlerMapping.BEST_MATCHING_HANDLER_ATTRIBUTE, + new ForwardUrlMappingInfo(controllerName: webRequest.controllerName)) controller as T } diff --git a/grails-web-core/src/main/resources/META-INF/additional-spring-configuration-metadata.json b/grails-web-core/src/main/resources/META-INF/additional-spring-configuration-metadata.json index 0f764ab2fe8..7a236c80de6 100644 --- a/grails-web-core/src/main/resources/META-INF/additional-spring-configuration-metadata.json +++ b/grails-web-core/src/main/resources/META-INF/additional-spring-configuration-metadata.json @@ -132,6 +132,12 @@ "description": "When true, XHR requests also respect the grails.mime.disable.accept.header.userAgents setting, while by default XHR requests ignore user agent filtering.", "defaultValue": false }, + { + "name": "grails.mime.negotiation.spring", + "type": "java.lang.Boolean", + "description": "Whether request.format, response.format, withFormat and the format respond writes in are resolved with Spring MVC's content negotiation manager, mapping the media types it resolves to the formats grails.mime.types gives them, rather than by the Grails rules. The format parameter, URL extensions and the grails.mime Accept header settings are kept, as strategies of Spring MVC's manager that also apply to what Spring MVC writes for the requests a URL mapping handles. Grails 9 negotiation stays the default in Grails 10.", + "defaultValue": false + }, { "name": "grails.converters.encoding", "type": "java.lang.String", From 56fa0da656200462e87e99f4cacc21087e71bb1f Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Sat, 14 Nov 2026 10:41:59 -0800 Subject: [PATCH 03/21] Match URL mappings for security when a request accepts no configured type ReflectionUtils.matchAllUrlMappings read the version of the response type, which grails.mime.negotiation.spring resolves to none for a request that accepts no configured type, such as one that sends only Accept: image/png, so every such request failed in the security filter with a NullPointerException. It now matches any version, as for a type without one. --- .../springsecurity/ReflectionUtils.groovy | 3 ++- .../springsecurity/ReflectionUtilsSpec.groovy | 21 +++++++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/grails-spring-security/plugin/src/main/groovy/grails/plugin/springsecurity/ReflectionUtils.groovy b/grails-spring-security/plugin/src/main/groovy/grails/plugin/springsecurity/ReflectionUtils.groovy index 5248fac5f11..1b1831212c5 100644 --- a/grails-spring-security/plugin/src/main/groovy/grails/plugin/springsecurity/ReflectionUtils.groovy +++ b/grails-spring-security/plugin/src/main/groovy/grails/plugin/springsecurity/ReflectionUtils.groovy @@ -212,7 +212,8 @@ class ReflectionUtils { // the mapping for a different action than the one about to execute - and authorize that one instead. // Under the servlet filter the request already reports the overridden method and this resolves to it. String method = HiddenHttpMethod.resolveOverride(grailsRequest.request) ?: grailsRequest.request.method - String version = grailsRequest.getHeader(ACCEPT_VERSION) ?: extension.getMimeTypeForRequest(grailsRequest).version + // none where the request accepts no configured type, as with grails.mime.negotiation.spring + String version = grailsRequest.getHeader(ACCEPT_VERSION) ?: extension.getMimeTypeForRequest(grailsRequest)?.version urlMappingsHolder.matchAll requestUrl, method, version == null ? UrlMapping.ANY_VERSION : version } diff --git a/grails-spring-security/plugin/src/test/groovy/grails/plugin/springsecurity/ReflectionUtilsSpec.groovy b/grails-spring-security/plugin/src/test/groovy/grails/plugin/springsecurity/ReflectionUtilsSpec.groovy index c4b380bae5a..78c5b1d1317 100644 --- a/grails-spring-security/plugin/src/test/groovy/grails/plugin/springsecurity/ReflectionUtilsSpec.groovy +++ b/grails-spring-security/plugin/src/test/groovy/grails/plugin/springsecurity/ReflectionUtilsSpec.groovy @@ -22,6 +22,7 @@ import org.springframework.http.HttpMethod import org.springframework.mock.web.MockHttpServletRequest import org.springframework.mock.web.MockHttpServletResponse +import grails.web.mapping.UrlMapping import grails.web.mapping.UrlMappingInfo import grails.web.mapping.UrlMappingsHolder import grails.web.mime.MimeType @@ -261,4 +262,24 @@ class ReflectionUtilsSpec extends AbstractUnitSpec { then: matchedWith == 'POST' } + + void 'url mappings are matched on any version for a request that accepts no configured type'() { + given: 'a request for which no type is resolved, as grails.mime.negotiation.spring resolves none for it' + def request = new MockHttpServletRequest(method: 'GET', requestURI: '/book') + request.addHeader('Accept', 'image/png') + def grailsRequest = new GrailsWebRequest(request, new MockHttpServletResponse(), servletContext) + + String matchedVersion = null + def holder = [matchAll: { String uri, String httpMethod, String version -> + matchedVersion = version + new UrlMappingInfo[0] + }] as UrlMappingsHolder + + when: + ReflectionUtils.matchAllUrlMappings(holder, '/book', grailsRequest, + [getMimeTypeForRequest: { Object... a -> null }] as HttpServletResponseExtension) + + then: + matchedVersion == UrlMapping.ANY_VERSION + } } From 11cb4b92d7c9d89690ffa8d310f6382a1ae98821 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Sat, 14 Nov 2026 10:41:59 -0800 Subject: [PATCH 04/21] Record every answer Grails and Spring MVC negotiation give differently FormatNegotiationComparisonSpec runs a matrix of requests a URL mapping handles through both policies, with and without grails.mime.negotiation.spring, under several grails.mime.types and Accept header configurations: Accept headers with qualities, wildcards and +json/+xml types, browser and XHR user agents, the format parameter, and Content-Type. It records each answer that differs, from response.format, withFormat, request.format and the media types Spring MVC's manager resolves for what it writes, so that a change to either policy that changes an answer fails it, and checks that with the setting the first type the manager resolves is of the format Grails resolves. --- .../FormatNegotiationComparisonSpec.groovy | 476 ++++++++++++++++++ 1 file changed, 476 insertions(+) create mode 100644 grails-mimetypes/src/test/groovy/org/grails/web/mime/FormatNegotiationComparisonSpec.groovy diff --git a/grails-mimetypes/src/test/groovy/org/grails/web/mime/FormatNegotiationComparisonSpec.groovy b/grails-mimetypes/src/test/groovy/org/grails/web/mime/FormatNegotiationComparisonSpec.groovy new file mode 100644 index 00000000000..8ec724d1d45 --- /dev/null +++ b/grails-mimetypes/src/test/groovy/org/grails/web/mime/FormatNegotiationComparisonSpec.groovy @@ -0,0 +1,476 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.grails.web.mime + +import org.springframework.context.ApplicationContext +import org.springframework.context.annotation.Bean +import org.springframework.context.annotation.Configuration +import org.springframework.context.annotation.Import +import org.springframework.core.env.ConfigurableEnvironment +import org.springframework.core.env.MapPropertySource +import org.springframework.mock.web.MockHttpServletRequest +import org.springframework.mock.web.MockHttpServletResponse +import org.springframework.mock.web.MockServletContext +import org.springframework.web.HttpMediaTypeNotAcceptableException +import org.springframework.web.accept.ContentNegotiationManager +import org.springframework.web.context.request.RequestContextHolder +import org.springframework.web.context.request.ServletWebRequest +import org.springframework.web.context.support.AnnotationConfigWebApplicationContext +import org.springframework.web.servlet.HandlerMapping +import org.springframework.web.servlet.config.annotation.EnableWebMvc + +import grails.config.Settings +import grails.core.DefaultGrailsApplication +import grails.core.GrailsApplication +import grails.util.GrailsWebMockUtil +import grails.web.mapping.UrlMappingInfo +import org.grails.config.PropertySourcesConfig +import org.grails.plugins.web.mime.MimeTypesConfiguration +import org.grails.web.servlet.mvc.GrailsWebRequest +import spock.lang.Shared +import spock.lang.Specification + +/** + * Runs a matrix of requests a URL mapping handles through Grails' negotiation and through Spring MVC's, which + * {@code grails.mime.negotiation.spring} selects, under several configurations, and records every answer that differs: + * the format {@code response.format} resolves, the block {@code withFormat} runs, the format {@code request.format} + * resolves and the media types Spring MVC's content negotiation manager resolves for what it writes for the request. + * The record is the evidence the upgrade guide summarizes, and a change to either policy that changes an answer fails it. + */ +class FormatNegotiationComparisonSpec extends Specification { + + private static final String CHROME = 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8' + + private static final String BROWSER = 'Mozilla/5.0 (X11; Linux x86_64; rv:140.0) Gecko/20100101 Firefox/140.0' + + /** The configurations the requests are negotiated under. */ + @Shared + Map> configurations = [ + 'defaults' : [:], + 'merged vendor type' : [(Settings.MIME_TYPES_MERGE_DEFAULTS): true, (Settings.MIME_TYPES): [ + all: '*/*', + vnd: 'application/vnd.app1.v1+json' + ]], + 'without all' : [(Settings.MIME_TYPES): [ + html: ['text/html', 'application/xhtml+xml'], + json: 'application/json', + xml : ['text/xml', 'application/xml'] + ]], + 'browser user agents' : [(Settings.MIME_DISABLE_ACCEPT_HEADER_FOR_USER_AGENTS): ['Gecko', 'WebKit', 'Presto', 'Trident']], + 'use.accept.header: false': [(Settings.MIME_USE_ACCEPT_HEADER): false] + ] + + /** + * The requests the configurations that change how the {@code Accept} header is read are negotiated with, which + * negotiate any other request as the defaults do. + */ + @Shared + Map>> acceptHeaderRequests = [ + 'browser user agents' : [ + [accept: 'application/json'], + [accept: 'application/json', userAgent: BROWSER], + [accept: 'application/json', userAgent: BROWSER, xhr: true], + [accept: CHROME, userAgent: BROWSER], + [accept: 'application/json', userAgent: BROWSER, format: 'xml'] + ], + 'use.accept.header: false': [ + [accept: 'application/json'], + [accept: CHROME], + [accept: 'application/json;q=abc'], + [accept: 'application/json', format: 'xml'] + ] + ] + + /** The requests, each with the headers and the format it is sent with. */ + @Shared + List> requests = [ + [:], + [accept: '*/*'], + [accept: 'text/html'], + [accept: CHROME], + [accept: 'application/json'], + [accept: 'Application/JSON'], + [accept: 'application/json;q=0.5, application/xml'], + [accept: '*/*, application/json'], + [accept: 'application/json, */*'], + [accept: 'application/xml, */*, text/html'], + [accept: 'text/*'], + [accept: 'application/*'], + [accept: 'application/problem+json'], + [accept: 'application/problem+xml'], + [accept: 'application/hal+json'], + [accept: 'application/vnd.api+json'], + [accept: 'application/soap+xml'], + [accept: 'application/xml, application/atom+xml'], + [accept: 'text/xml;q=0.5, application/xml;q=0.9, application/json;q=0.7'], + [accept: 'application/json;q=0, */*;q=0.1'], + [accept: 'image/png'], + [accept: 'application/json;q=abc'], + [accept: '*'], + [accept: 'application/json', userAgent: BROWSER], + [accept: 'application/json', userAgent: BROWSER, xhr: true], + [accept: CHROME, userAgent: BROWSER], + [accept: 'application/json', format: 'xml'], + [accept: 'application/json', format: 'html'], + [accept: 'application/json', format: 'all'], + [accept: 'application/json', format: 'unknown'], + [accept: 'text/html', format: 'json'], + [contentType: 'application/json;charset=UTF-8'], + [contentType: 'text/xml'], + [contentType: 'application/vnd.api+json'], + [contentType: 'application/problem+json'], + [contentType: 'application/json, application/xml'], + [contentType: 'application/json;charset='], + [contentType: 'image/png'] + ] + + /** Every answer that differs, as {@code configuration | request | answer: Grails 9 -> Spring}. */ + private static final List RECORDED = [ + 'defaults | Accept: */*, application/json | response.format: all -> json', + 'defaults | Accept: */*, application/json | withFormat(html, json, xml): html -> json', + 'defaults | Accept: */*, application/json | withFormat(json, xml, *): * -> json', + 'defaults | Accept: application/xml, */*, text/html | withFormat(pdf, html): pdf -> html', + 'defaults | Accept: text/* | withFormat(pdf, html): pdf -> html', + 'defaults | Accept: application/vnd.api+json | response.format: all -> json', + 'defaults | Accept: application/vnd.api+json | withFormat(html, json, xml): html -> json', + 'defaults | Accept: application/vnd.api+json | withFormat(json, xml, *): * -> json', + 'defaults | Accept: application/vnd.api+json | withFormat(pdf, html): pdf -> null', + 'defaults | Accept: application/soap+xml | response.format: all -> xml', + 'defaults | Accept: application/soap+xml | withFormat(html, json, xml): html -> xml', + 'defaults | Accept: application/soap+xml | withFormat(json, xml, *): * -> xml', + 'defaults | Accept: application/soap+xml | withFormat(pdf, html): pdf -> null', + 'defaults | Accept: application/xml, application/atom+xml | response.format: atom -> xml', + 'defaults | Accept: image/png | response.format: all -> null', + 'defaults | Accept: image/png | withFormat(html, json, xml): html -> null', + 'defaults | Accept: image/png | withFormat(pdf, html): pdf -> null', + 'defaults | Accept: application/json;q=abc | response.format: json -> null', + 'defaults | Accept: application/json;q=abc | withFormat(html, json, xml): json -> null', + 'defaults | Accept: application/json;q=abc | withFormat(json, xml, *): json -> *', + 'defaults | Accept: application/json, format=xml | Spring MVC: [application/json] -> [text/xml, application/xml, application/*+xml]', + 'defaults | Accept: application/json, format=html | Spring MVC: [application/json] -> [text/html, application/xhtml+xml]', + 'defaults | Accept: application/json, format=all | response.format: all -> json', + 'defaults | Accept: application/json, format=all | withFormat(html, json, xml): html -> json', + 'defaults | Accept: application/json, format=all | withFormat(json, xml, *): * -> json', + 'defaults | Accept: application/json, format=all | withFormat(pdf, html): pdf -> null', + 'defaults | Accept: application/json, format=unknown | response.format: all -> null', + 'defaults | Accept: application/json, format=unknown | withFormat(html, json, xml): html -> json', + 'defaults | Accept: application/json, format=unknown | withFormat(json, xml, *): * -> json', + 'defaults | Accept: application/json, format=unknown | withFormat(pdf, html): pdf -> null', + 'defaults | Accept: application/json, format=unknown | Spring MVC: [application/json] -> not acceptable', + 'defaults | Accept: text/html, format=json | Spring MVC: [text/html] -> [application/json, text/json, application/*+json]', + 'defaults | Content-Type: application/vnd.api+json | request.format: null -> json', + 'defaults | Content-Type: application/json, application/xml | request.format: json -> null', + 'defaults | Content-Type: application/json;charset= | request.format: json -> null', + 'merged vendor type | Accept: */*, application/json | response.format: all -> json', + 'merged vendor type | Accept: */*, application/json | withFormat(html, json, xml): html -> json', + 'merged vendor type | Accept: */*, application/json | withFormat(json, xml, *): * -> json', + 'merged vendor type | Accept: application/xml, */*, text/html | withFormat(pdf, html): pdf -> html', + 'merged vendor type | Accept: text/* | withFormat(pdf, html): pdf -> html', + 'merged vendor type | Accept: application/vnd.api+json | response.format: all -> json', + 'merged vendor type | Accept: application/vnd.api+json | withFormat(html, json, xml): html -> json', + 'merged vendor type | Accept: application/vnd.api+json | withFormat(json, xml, *): * -> json', + 'merged vendor type | Accept: application/vnd.api+json | withFormat(pdf, html): pdf -> null', + 'merged vendor type | Accept: application/soap+xml | response.format: all -> xml', + 'merged vendor type | Accept: application/soap+xml | withFormat(html, json, xml): html -> xml', + 'merged vendor type | Accept: application/soap+xml | withFormat(json, xml, *): * -> xml', + 'merged vendor type | Accept: application/soap+xml | withFormat(pdf, html): pdf -> null', + 'merged vendor type | Accept: application/xml, application/atom+xml | response.format: atom -> xml', + 'merged vendor type | Accept: image/png | response.format: all -> null', + 'merged vendor type | Accept: image/png | withFormat(html, json, xml): html -> null', + 'merged vendor type | Accept: image/png | withFormat(pdf, html): pdf -> null', + 'merged vendor type | Accept: application/json;q=abc | response.format: json -> null', + 'merged vendor type | Accept: application/json;q=abc | withFormat(html, json, xml): json -> null', + 'merged vendor type | Accept: application/json;q=abc | withFormat(json, xml, *): json -> *', + 'merged vendor type | Accept: application/json, format=xml | Spring MVC: [application/json] -> [text/xml, application/xml, application/*+xml]', + 'merged vendor type | Accept: application/json, format=html | Spring MVC: [application/json] -> [text/html, application/xhtml+xml]', + 'merged vendor type | Accept: application/json, format=all | response.format: all -> json', + 'merged vendor type | Accept: application/json, format=all | withFormat(html, json, xml): html -> json', + 'merged vendor type | Accept: application/json, format=all | withFormat(json, xml, *): * -> json', + 'merged vendor type | Accept: application/json, format=all | withFormat(pdf, html): pdf -> null', + 'merged vendor type | Accept: application/json, format=unknown | response.format: all -> null', + 'merged vendor type | Accept: application/json, format=unknown | withFormat(html, json, xml): html -> json', + 'merged vendor type | Accept: application/json, format=unknown | withFormat(json, xml, *): * -> json', + 'merged vendor type | Accept: application/json, format=unknown | withFormat(pdf, html): pdf -> null', + 'merged vendor type | Accept: application/json, format=unknown | Spring MVC: [application/json] -> not acceptable', + 'merged vendor type | Accept: text/html, format=json | Spring MVC: [text/html] -> [application/json, text/json, application/*+json]', + 'merged vendor type | Content-Type: application/vnd.api+json | request.format: null -> json', + 'merged vendor type | Content-Type: application/json, application/xml | request.format: json -> null', + 'merged vendor type | Content-Type: application/json;charset= | request.format: json -> null', + 'without all | no headers | response.format: html -> all', + 'without all | no headers | withFormat(json, xml, *): json -> *', + 'without all | no headers | withFormat(pdf, html): html -> pdf', + 'without all | Accept: */*, application/json | withFormat(pdf, html): null -> pdf', + 'without all | Accept: application/json, */* | withFormat(pdf, html): null -> pdf', + 'without all | Accept: text/* | withFormat(pdf, html): pdf -> html', + 'without all | Accept: application/* | withFormat(pdf, html): pdf -> html', + 'without all | Accept: application/hal+json | response.format: all -> json', + 'without all | Accept: application/hal+json | withFormat(html, json, xml): html -> json', + 'without all | Accept: application/hal+json | withFormat(json, xml, *): * -> json', + 'without all | Accept: application/hal+json | withFormat(pdf, html): pdf -> null', + 'without all | Accept: application/vnd.api+json | response.format: all -> json', + 'without all | Accept: application/vnd.api+json | withFormat(html, json, xml): html -> json', + 'without all | Accept: application/vnd.api+json | withFormat(json, xml, *): * -> json', + 'without all | Accept: application/vnd.api+json | withFormat(pdf, html): pdf -> null', + 'without all | Accept: application/soap+xml | response.format: all -> xml', + 'without all | Accept: application/soap+xml | withFormat(html, json, xml): html -> xml', + 'without all | Accept: application/soap+xml | withFormat(json, xml, *): * -> xml', + 'without all | Accept: application/soap+xml | withFormat(pdf, html): pdf -> null', + 'without all | Accept: application/json;q=0, */*;q=0.1 | response.format: json -> all', + 'without all | Accept: application/json;q=0, */*;q=0.1 | withFormat(html, json, xml): json -> html', + 'without all | Accept: application/json;q=0, */*;q=0.1 | withFormat(json, xml, *): json -> *', + 'without all | Accept: application/json;q=0, */*;q=0.1 | withFormat(pdf, html): null -> pdf', + 'without all | Accept: image/png | response.format: all -> null', + 'without all | Accept: image/png | withFormat(html, json, xml): html -> null', + 'without all | Accept: image/png | withFormat(pdf, html): pdf -> null', + 'without all | Accept: application/json;q=abc | response.format: json -> null', + 'without all | Accept: application/json;q=abc | withFormat(html, json, xml): json -> null', + 'without all | Accept: application/json;q=abc | withFormat(json, xml, *): json -> *', + 'without all | Accept: application/json, format=xml | Spring MVC: [application/json] -> [text/xml, application/xml, application/*+xml]', + 'without all | Accept: application/json, format=html | Spring MVC: [application/json] -> [text/html, application/xhtml+xml]', + 'without all | Accept: application/json, format=all | response.format: html -> null', + 'without all | Accept: application/json, format=all | withFormat(html, json, xml): html -> json', + 'without all | Accept: application/json, format=all | withFormat(pdf, html): html -> null', + 'without all | Accept: application/json, format=all | Spring MVC: [application/json] -> not acceptable', + 'without all | Accept: application/json, format=unknown | response.format: html -> null', + 'without all | Accept: application/json, format=unknown | withFormat(html, json, xml): html -> json', + 'without all | Accept: application/json, format=unknown | withFormat(pdf, html): html -> null', + 'without all | Accept: application/json, format=unknown | Spring MVC: [application/json] -> not acceptable', + 'without all | Accept: text/html, format=json | Spring MVC: [text/html] -> [application/json, application/*+json]', + 'without all | Content-Type: application/json;charset=UTF-8 | response.format: html -> all', + 'without all | Content-Type: application/json;charset=UTF-8 | withFormat(json, xml, *): json -> *', + 'without all | Content-Type: application/json;charset=UTF-8 | withFormat(pdf, html): html -> pdf', + 'without all | Content-Type: text/xml | response.format: html -> all', + 'without all | Content-Type: text/xml | withFormat(json, xml, *): json -> *', + 'without all | Content-Type: text/xml | withFormat(pdf, html): html -> pdf', + 'without all | Content-Type: application/vnd.api+json | response.format: html -> all', + 'without all | Content-Type: application/vnd.api+json | withFormat(json, xml, *): json -> *', + 'without all | Content-Type: application/vnd.api+json | withFormat(pdf, html): html -> pdf', + 'without all | Content-Type: application/vnd.api+json | request.format: null -> json', + 'without all | Content-Type: application/problem+json | response.format: html -> all', + 'without all | Content-Type: application/problem+json | withFormat(json, xml, *): json -> *', + 'without all | Content-Type: application/problem+json | withFormat(pdf, html): html -> pdf', + 'without all | Content-Type: application/json, application/xml | response.format: html -> all', + 'without all | Content-Type: application/json, application/xml | withFormat(json, xml, *): json -> *', + 'without all | Content-Type: application/json, application/xml | withFormat(pdf, html): html -> pdf', + 'without all | Content-Type: application/json, application/xml | request.format: json -> null', + 'without all | Content-Type: application/json;charset= | response.format: html -> all', + 'without all | Content-Type: application/json;charset= | withFormat(json, xml, *): json -> *', + 'without all | Content-Type: application/json;charset= | withFormat(pdf, html): html -> pdf', + 'without all | Content-Type: application/json;charset= | request.format: json -> null', + 'without all | Content-Type: image/png | response.format: html -> all', + 'without all | Content-Type: image/png | withFormat(json, xml, *): json -> *', + 'without all | Content-Type: image/png | withFormat(pdf, html): html -> pdf', + 'browser user agents | Accept: application/json, browser User-Agent | Spring MVC: [application/json] -> [*/*]', + 'browser user agents | Accept: , browser User-Agent | Spring MVC: [text/html, application/xhtml+xml, image/avif, image/webp, application/xml;q=0.9, */*;q=0.8] -> [*/*]', + 'browser user agents | Accept: application/json, browser User-Agent, format=xml | Spring MVC: [application/json] -> [text/xml, application/xml, application/*+xml]', + 'use.accept.header: false | Accept: application/json | Spring MVC: [application/json] -> [*/*]', + 'use.accept.header: false | Accept: | Spring MVC: [text/html, application/xhtml+xml, image/avif, image/webp, application/xml;q=0.9, */*;q=0.8] -> [*/*]', + 'use.accept.header: false | Accept: application/json;q=abc | Spring MVC: not acceptable -> [*/*]', + 'use.accept.header: false | Accept: application/json, format=xml | Spring MVC: [application/json] -> [text/xml, application/xml, application/*+xml]' + ] + + @Shared + Map contexts = [:] + + void cleanupSpec() { + contexts.values()*.close() + } + + void cleanup() { + RequestContextHolder.resetRequestAttributes() + } + + void 'every answer that differs between the two policies is recorded'() { + when: + List differences = [] + configurations.each { String configuration, Map properties -> + for (Map sent in requestsFor(configuration)) { + Map grails = answers(configuration, properties, sent, false) + Map spring = answers(configuration, properties, sent, true) + grails.each { String answer, Object value -> + if (value != spring[answer]) { + differences << "${configuration} | ${describe(sent)} | ${answer}: ${value} -> ${spring[answer]}".toString() + } + } + } + } + + then: + differences == RECORDED + } + + void "with the setting, the first type Spring MVC's manager resolves for a request a URL mapping handles is of the format Grails resolves"() { + when: 'the format of the first media type the manager resolves for each request of the matrix is not the one response.format resolves' + List diverging = [] + configurations.each { String configuration, Map properties -> + requestsFor(configuration).findAll { !it.contentType }.each { Map sent -> + Map spring = answers(configuration, properties, sent, true) + Object format = spring['Spring MVC'] == 'not acceptable' ? null : formatOf(configuration, properties, sent) + if (spring['response.format'] != format) { + diverging << "${configuration} | ${describe(sent)} | ${spring['response.format']} -> ${format}".toString() + } + } + } + + then: + diverging.isEmpty() + } + + private Map answers(String configuration, Map properties, Map sent, + boolean springNegotiation) { + Map answers = [:] + answers['response.format'] = respond(configuration, properties, sent, springNegotiation) { GrailsWebRequest webRequest -> + webRequest.currentResponse.format + } + answers['withFormat(html, json, xml)'] = respond(configuration, properties, sent, springNegotiation) { GrailsWebRequest webRequest -> + webRequest.currentResponse.withFormat { + html { 'html' } + json { 'json' } + xml { 'xml' } + } + } + answers['withFormat(json, xml, *)'] = respond(configuration, properties, sent, springNegotiation) { GrailsWebRequest webRequest -> + webRequest.currentResponse.withFormat { + json { 'json' } + xml { 'xml' } + '*' { '*' } + } + } + answers['withFormat(pdf, html)'] = respond(configuration, properties, sent, springNegotiation) { GrailsWebRequest webRequest -> + webRequest.currentResponse.withFormat { + pdf { 'pdf' } + html { 'html' } + } + } + if (sent.contentType) { + answers['request.format'] = respond(configuration, properties, sent, springNegotiation) { GrailsWebRequest webRequest -> + webRequest.currentRequest.format + } + } + answers['Spring MVC'] = respond(configuration, properties, sent, springNegotiation) { GrailsWebRequest webRequest -> + try { + manager(configuration, properties, springNegotiation).resolveMediaTypes(new ServletWebRequest(webRequest.currentRequest)).toString() + } + catch (HttpMediaTypeNotAcceptableException ignored) { + 'not acceptable' + } + } + answers + } + + /** + * The format of the first media type Spring MVC's manager resolves for a request, as Grails resolves an + * {@code Accept} header of that type alone under the MIME types of the configuration. + */ + private Object formatOf(String configuration, Map properties, Map sent) { + Object first = respond(configuration, properties, sent, true) { GrailsWebRequest webRequest -> + manager(configuration, properties, true).resolveMediaTypes(new ServletWebRequest(webRequest.currentRequest)).first() + } + Map types = properties.findAll { String key, Object value -> key.startsWith('grails.mime.types') || key == Settings.MIME_TYPES_MERGE_DEFAULTS } + respond("${configuration} types".toString(), types, [accept: first.toString()], true) { GrailsWebRequest webRequest -> + webRequest.currentResponse.format + } + } + + private List> requestsFor(String configuration) { + acceptHeaderRequests[configuration] ?: requests + } + + private Object respond(String configuration, Map properties, Map sent, + boolean springNegotiation, Closure answer) { + AnnotationConfigWebApplicationContext context = context(configuration, properties, springNegotiation) + def request = new MockHttpServletRequest(context.servletContext) + if (sent.accept) { + request.addHeader('Accept', sent.accept) + } + if (sent.userAgent) { + request.addHeader('User-Agent', sent.userAgent) + } + if (sent.xhr) { + request.addHeader('X-Requested-With', 'XMLHttpRequest') + } + if (sent.contentType) { + request.contentType = sent.contentType + } + request.setAttribute(HandlerMapping.BEST_MATCHING_HANDLER_ATTRIBUTE, Stub(UrlMappingInfo)) + GrailsWebRequest webRequest = GrailsWebMockUtil.bindMockWebRequest(context, request, new MockHttpServletResponse()) + if (sent.format) { + webRequest.params.format = sent.format + } + try { + return answer.call(webRequest) + } + finally { + RequestContextHolder.resetRequestAttributes() + } + } + + private ContentNegotiationManager manager(String configuration, Map properties, boolean springNegotiation) { + context(configuration, properties, springNegotiation) + .getBean(GrailsContentNegotiationStrategy.MVC_CONTENT_NEGOTIATION_MANAGER, ContentNegotiationManager) + } + + private AnnotationConfigWebApplicationContext context(String configuration, Map properties, + boolean springNegotiation) { + contexts.computeIfAbsent("${configuration}:${springNegotiation}".toString()) { + def context = new AnnotationConfigWebApplicationContext() + context.servletContext = new MockServletContext() + context.environment.propertySources.addFirst(new MapPropertySource('test', + properties + [(Settings.MIME_NEGOTIATION_SPRING): springNegotiation])) + context.register(ComparisonConfiguration) + context.refresh() + context + } + } + + private static String describe(Map sent) { + List parts = [] + if (sent.accept) { + parts << "Accept: ${sent.accept == CHROME ? '' : sent.accept}".toString() + } + if (sent.userAgent) { + parts << 'browser User-Agent' + } + if (sent.xhr) { + parts << 'XHR' + } + if (sent.format) { + parts << "format=${sent.format}".toString() + } + if (sent.contentType) { + parts << "Content-Type: ${sent.contentType}".toString() + } + parts ? parts.join(', ') : 'no headers' + } + + @Configuration(proxyBeanMethods = false) + @EnableWebMvc + @Import(MimeTypesConfiguration) + static class ComparisonConfiguration { + + @Bean + GrailsApplication grailsApplication(ApplicationContext applicationContext, ConfigurableEnvironment environment) { + def application = new DefaultGrailsApplication() + application.config = new PropertySourcesConfig(environment.propertySources) + application.applicationContext = applicationContext + application.mainContext = applicationContext + application + } + } +} From 1982f075152024fdb81c064c02754691ae43335a Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Sat, 14 Nov 2026 10:41:59 -0800 Subject: [PATCH 05/21] Test Spring MVC format negotiation end to end app1 answers the same requests with and without grails.mime.negotiation.spring: a ResponseEntity an action returns is written in the format of its URL extension, or not acceptable where no converter writes it so, an unknown format is not acceptable, the formats Grails resolves follow Spring MVC's order, a +json body is of the json format, and a Spring MVC endpoint keeps its negotiation. --- .../contentneg/SpringWrittenController.groovy | 40 +++++++ .../init/functionaltests/Application.groovy | 11 ++ .../SpringFormatNegotiationSpec.groovy | 105 ++++++++++++++++++ .../contentneg/SpringNegotiationApi.groovy | 35 ++++++ 4 files changed, 191 insertions(+) create mode 100644 grails-test-examples/app1/grails-app/controllers/functionaltests/contentneg/SpringWrittenController.groovy create mode 100644 grails-test-examples/app1/src/integration-test/groovy/functionaltests/contentneg/SpringFormatNegotiationSpec.groovy create mode 100644 grails-test-examples/app1/src/main/groovy/functionaltests/contentneg/SpringNegotiationApi.groovy diff --git a/grails-test-examples/app1/grails-app/controllers/functionaltests/contentneg/SpringWrittenController.groovy b/grails-test-examples/app1/grails-app/controllers/functionaltests/contentneg/SpringWrittenController.groovy new file mode 100644 index 00000000000..a07bf04f2b2 --- /dev/null +++ b/grails-test-examples/app1/grails-app/controllers/functionaltests/contentneg/SpringWrittenController.groovy @@ -0,0 +1,40 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package functionaltests.contentneg + +import org.springframework.http.ResponseEntity + +/** + * Actions whose values Spring MVC writes, and one that answers with the formats Grails resolves for the request, which + * {@code grails.mime.negotiation.spring} negotiates alike. + */ +class SpringWrittenController { + + def entity() { + ResponseEntity.ok([title: 'Grails']) + } + + def text() { + ResponseEntity.ok('Grails') + } + + def formats() { + render(contentType: 'text/plain', text: "${response.format}|${request.format}") + } +} diff --git a/grails-test-examples/app1/grails-app/init/functionaltests/Application.groovy b/grails-test-examples/app1/grails-app/init/functionaltests/Application.groovy index dcc99a5d58b..4019ce93a86 100644 --- a/grails-test-examples/app1/grails-app/init/functionaltests/Application.groovy +++ b/grails-test-examples/app1/grails-app/init/functionaltests/Application.groovy @@ -19,8 +19,11 @@ package functionaltests +import org.springframework.context.annotation.Bean + import grails.boot.GrailsApp import grails.boot.config.GrailsAutoConfiguration +import functionaltests.contentneg.SpringNegotiationApi class Application extends GrailsAutoConfiguration { static { @@ -30,4 +33,12 @@ class Application extends GrailsAutoConfiguration { static void main(String[] args) { GrailsApp.run(Application) } + + /** + * A Spring MVC endpoint beside the Grails controllers, which content negotiation leaves to Spring MVC. + */ + @Bean + SpringNegotiationApi springNegotiationApi() { + new SpringNegotiationApi() + } } diff --git a/grails-test-examples/app1/src/integration-test/groovy/functionaltests/contentneg/SpringFormatNegotiationSpec.groovy b/grails-test-examples/app1/src/integration-test/groovy/functionaltests/contentneg/SpringFormatNegotiationSpec.groovy new file mode 100644 index 00000000000..e7f691c56fd --- /dev/null +++ b/grails-test-examples/app1/src/integration-test/groovy/functionaltests/contentneg/SpringFormatNegotiationSpec.groovy @@ -0,0 +1,105 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package functionaltests.contentneg + +import org.springframework.test.context.TestPropertySource +import spock.lang.Specification +import spock.lang.Tag + +import grails.testing.mixin.integration.Integration +import org.apache.grails.testing.http.client.HttpClientSupport + +/** + * With {@code grails.mime.negotiation.spring}, Grails formats are resolved with Spring MVC's content negotiation, and + * what Spring MVC writes for an action is negotiated with the format the request names, while a Spring MVC endpoint is + * negotiated as before. + */ +@Integration +@Tag('http-client') +@TestPropertySource(properties = 'grails.mime.negotiation.spring=true') +class SpringFormatNegotiationSpec extends Specification implements HttpClientSupport { + + void 'a value Spring MVC writes for an action is in the format of its URL extension, which a map cannot be written in as HTML'() { + expect: + http('/springWritten/entity.html', Accept: '*/*').assertStatus(406) + http('/springWritten/entity.json', Accept: 'text/html').assertStatus(200).contentType.startsWith('application/json') + } + + void 'a text Spring MVC writes for an action is labelled with the format of its URL extension'() { + expect: + http('/springWritten/text.json', Accept: 'text/plain').assertStatus(200).contentType.startsWith('application/json') + } + + void 'a request that names a format no type is configured for is not acceptable'() { + expect: + http('/springWritten/entity?format=unknown', Accept: 'application/json').assertStatus(406) + } + + void 'the formats Grails resolves follow the order Spring MVC resolves the Accept header in: #accept'() { + expect: + http('/springWritten/formats', Accept: accept).assertStatus(200).assertEquals(formats) + + where: + accept || formats + '*/*, application/json' || 'json|all' + 'image/png' || 'null|all' + 'application/soap+xml' || 'xml|all' + } + + void 'a body of a type with the +json suffix is of the json format'() { + expect: + http('/springWritten/formats', Accept: 'application/json', 'Content-Type': 'application/merge-patch+json') + .assertStatus(200).assertEquals('json|json') + } + + void 'a Spring MVC endpoint keeps its negotiation: #description'() { + expect: + http("/springNegotiation${query}", Accept: accept).assertStatus(status) + + where: + description | query | accept || status + 'the format parameter is ignored' | '?format=xml' | 'application/json' || 200 + 'an unknown type is not acceptable' | '' | 'image/png' || 406 + } +} + +/** + * Without {@code grails.mime.negotiation.spring}, Grails resolves formats with its own rules, and Spring MVC writes the + * values of actions as the {@code Accept} header asks. + */ +@Integration +@Tag('http-client') +class GrailsFormatNegotiationSpec extends Specification implements HttpClientSupport { + + void 'a value Spring MVC writes for an action is in the type the Accept header asks for, whatever its URL extension'() { + expect: + http('/springWritten/entity.html', Accept: '*/*').assertStatus(200).contentType.startsWith('application/json') + http('/springWritten/text.json', Accept: 'text/plain').assertStatus(200).contentType.startsWith('text/plain') + } + + void 'the formats Grails resolves follow the Grails rules: #accept'() { + expect: + http('/springWritten/formats', Accept: accept).assertStatus(200).assertEquals(formats) + + where: + accept || formats + '*/*, application/json' || 'all|all' + 'image/png' || 'all|all' + } +} diff --git a/grails-test-examples/app1/src/main/groovy/functionaltests/contentneg/SpringNegotiationApi.groovy b/grails-test-examples/app1/src/main/groovy/functionaltests/contentneg/SpringNegotiationApi.groovy new file mode 100644 index 00000000000..e50b73ae05c --- /dev/null +++ b/grails-test-examples/app1/src/main/groovy/functionaltests/contentneg/SpringNegotiationApi.groovy @@ -0,0 +1,35 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package functionaltests.contentneg + +import org.springframework.web.bind.annotation.GetMapping +import org.springframework.web.bind.annotation.RestController + +/** + * A Spring MVC endpoint beside the Grails controllers, whose content negotiation {@code grails.mime.negotiation.spring} + * leaves as Spring MVC configures it. + */ +@RestController +class SpringNegotiationApi { + + @GetMapping('/springNegotiation') + Map negotiation() { + [title: 'Grails'] + } +} From c901261665fe77f44da31609a46d418f22d2d347 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Sat, 14 Nov 2026 10:41:59 -0800 Subject: [PATCH 06/21] Document grails.mime.negotiation.spring The content negotiation guide describes how the setting resolves formats with Spring MVC's manager and what becomes of each Grails rule: kept, extended or dropped. The new Upgrading from Grails 9 to Grails 10 section lists the answers that change, which FormatNegotiationComparisonSpec records, and the built-in properties list the setting. --- .../en/guide/conf/config/builtInOptions.adoc | 1 + .../guide/theWebLayer/contentNegotiation.adoc | 81 +++++++++++++++++++ grails-doc/src/en/guide/toc.yml | 1 + .../src/en/guide/upgrading/upgrading100x.adoc | 80 ++++++++++++++++++ 4 files changed, 163 insertions(+) create mode 100644 grails-doc/src/en/guide/upgrading/upgrading100x.adoc diff --git a/grails-doc/src/en/guide/conf/config/builtInOptions.adoc b/grails-doc/src/en/guide/conf/config/builtInOptions.adoc index 64ffb941a45..7828aba7588 100644 --- a/grails-doc/src/en/guide/conf/config/builtInOptions.adoc +++ b/grails-doc/src/en/guide/conf/config/builtInOptions.adoc @@ -34,6 +34,7 @@ On the runtime front, i.e. `grails-app/conf/application.yml`, there are quite a * `grails.views.gsp.encoding` - The file encoding used for GSP source files (default: 'utf-8'). * `grails.mime.file.extensions` - Whether to use the file extension to dictate the mime type in link:theWebLayer.html#contentNegotiation[Content Negotiation] (default: true). * `grails.mime.types` - A map of supported mime types used for link:theWebLayer.html#contentNegotiation[Content Negotiation]. +* `grails.mime.negotiation.spring` - Whether `request.format`, `response.format`, `withFormat` and the format `respond` writes in are resolved with Spring MVC's content negotiation manager, as the formats `grails.mime.types` gives the media types it resolves, rather than by the Grails rules; the `format` parameter, URL extensions and the `grails.mime` settings of the `Accept` header then also decide what Spring MVC writes for an action (default: false). See <>. * `grails.serverURL` - A string specifying the server URL portion of absolute links, including server name e.g. grails.serverURL="https://my.yourportal.com". See link:{gspTagsRef}createLink.html[createLink]. Also used by redirects. * `grails.views.gsp.layout.preprocess` - Determines whether layout preprocessing happens. Disabling this slows down page rendering, but if you need Grails' layout implementation to parse the generated HTML from a GSP view, then disabling it is the right option. Don't worry if you don't understand this advanced property: leave it set to true. * `grails.reload.excludes` and `grails.reload.includes` - Configuring these directives determines the reload behavior for project specific source files. Each directive takes a list of strings that are the class names for project source files that should be excluded from reloading behavior or included accordingly when running the application in development with the `bootRun` task. If the `grails.reload.includes` directive is configured, then only the classes in that list will be reloaded. diff --git a/grails-doc/src/en/guide/theWebLayer/contentNegotiation.adoc b/grails-doc/src/en/guide/theWebLayer/contentNegotiation.adoc index e878767b4e7..797b16a7ba5 100644 --- a/grails-doc/src/en/guide/theWebLayer/contentNegotiation.adoc +++ b/grails-doc/src/en/guide/theWebLayer/contentNegotiation.adoc @@ -263,6 +263,87 @@ Note the inclusion of the `format` variable in the path. If you do not wish to u +[[springFormatNegotiation]] +==== Resolving Formats with Spring MVC Content Negotiation + +Grails resolves `request.format`, `response.format`, `withFormat` and the format `respond` writes in by the rules this +section describes, while Spring MVC's content negotiation manager decides the type of what Spring MVC writes for an +action: a `ResponseEntity`, a `ProblemDetail` or another value an action returns (see +<>), a problem `respond` writes, and the JSON `respond` writes with +Spring MVC. The two can answer one request differently. Set `grails.mime.negotiation.spring` to `true` to resolve the +Grails formats with Spring MVC's manager too: + +[source,yaml] +.grails-app/conf/application.yml +---- +grails: + mime: + negotiation: + spring: true +---- + +Grails {grailsMajorVersion} keeps the Grails rules by default. With the setting: + +* The `Accept` header is read by Spring MVC's manager, with its strategies, so the `spring.mvc.contentnegotiation.*` +properties apply to the Grails formats as they do to Spring MVC, and its media types are taken in the order Spring MVC +takes them: by quality, then a more specific type ahead of a less specific one, then in the order the header lists them. +`Accept: */*, application/json` is the `json` format, where the Grails rules give `all`, and +`Accept: application/xml, application/atom+xml` is `xml`, where they give `atom`. +* Each media type is the format `grails.mime.types`, or a `MimeTypeProvider` bean such as a renderer, gives it. A type +with the `+json` or `+xml` suffix that no configured type names, such as `application/merge-patch+json` or +`application/problem+xml`, is the `json` or the `xml` format, as Spring MVC's JSON and XML converters write such types. +* `*/*` is the `all` format, also where `grails.mime.types` does not list it. So is another wildcard, such as `text/*`, +for which `withFormat` runs its `*` block or else the first block of a format with a type compatible with the wildcard, +and `respond` answers in the first of the action's formats with such a type, as Spring MVC answers a wildcard with the +first of its candidates that is compatible with it. +* A request that accepts no configured type, such as one that sends only `Accept: image/png`, or whose `Accept` header +Spring cannot read, has no format: `response.format` and `response.mimeType` are `null`, `respond` answers +`406 Not Acceptable`, and `withFormat` runs its `*` block, or no block. The Grails rules answer such a request as one +that accepts any type, with the `all` format. +* The `format` parameter and a URL extension name the format, ahead of the `Accept` header, as before. The first value +of the parameter counts, as for Spring MVC; a format no type is configured for is not acceptable, where the Grails rules +answer in the first configured format; and the `all` format leaves the format to the `Accept` header. +* `grails.mime.use.accept.header` and `grails.mime.disable.accept.header.*` ignore the `Accept` header as before. +* The `format` parameter, the URL extension and the `Accept` header settings also decide what Spring MVC writes for a +request a URL mapping handles, so that it is in the format Grails resolves for the request: an action that returns a +`ResponseEntity` of a map answers `/book/show/1.json` in JSON whatever the `Accept` header asks for, and +`/book/show/1.html` with `406 Not Acceptable`, since no message converter writes a map as HTML. +* `request.format` reads the `Content-Type` header as Spring reads it, as one media type, which is the format the +`Accept` header would make it: a body sent as `application/merge-patch+json` is of the `json` format, and data binding +reads it as JSON. A type no configured type stands for, or that Spring cannot read, is of no format, and a request +without a `Content-Type` is of the first configured format, as before. + +A Spring MVC endpoint, such as an `@RestController` or an actuator endpoint, and Spring Security, whose filters negotiate +before a URL mapping has matched the request, negotiate as before: the setting changes no answer Spring MVC gives a request +no URL mapping handles. Each rule of Grails' negotiation becomes: + +[cols="2,3"] +|=== +|Grails rule |With `grails.mime.negotiation.spring` + +|The `format` parameter and URL extensions select the format +|Kept, ahead of Spring MVC's strategies, and also for what Spring MVC writes for the request. An unknown format is not +acceptable, and the `all` format leaves the choice to the `Accept` header. + +|`grails.mime.use.accept.header` and `grails.mime.disable.accept.header.*` ignore the `Accept` header +|Kept, also for what Spring MVC writes for the request. + +|`text/xml` and `application/xml` are merged into one `xml` type +|Dropped: both are the `xml` format, which comes in Spring MVC's order. + +|A type with the `+xml` suffix comes ahead of `application/xml` of equal quality +|Dropped: the types come in Spring MVC's order. + +|The problem types of RFC 9457 are the `json` and `xml` formats +|Extended to any type with the `+json` or `+xml` suffix that no configured type names. + +|A request that accepts no configured type is answered as one that accepts any type, and one that names a format no +type is configured for in the first configured format +|Dropped: such a request, and one whose `Accept` header Spring cannot read, is not acceptable. +|=== + +See xref:upgrading#upgrading100x[Upgrading from Grails 9 to Grails 10] for how each answer changes. + ==== Testing Content Negotiation diff --git a/grails-doc/src/en/guide/toc.yml b/grails-doc/src/en/guide/toc.yml index 25fe7b73d95..6d49075f174 100644 --- a/grails-doc/src/en/guide/toc.yml +++ b/grails-doc/src/en/guide/toc.yml @@ -37,6 +37,7 @@ gettingStarted: developmentReloading: Development Reloading upgrading: title: Upgrading from the previous versions + upgrading100x: Upgrading from Grails 9 to Grails 10 upgrading90x: Upgrading from Grails 8 to Grails 9 upgrading81x: Upgrading from Grails 8.0 to Grails 8.1 upgrading80x: Upgrading from Grails 7 to Grails 8 diff --git a/grails-doc/src/en/guide/upgrading/upgrading100x.adoc b/grails-doc/src/en/guide/upgrading/upgrading100x.adoc new file mode 100644 index 00000000000..eecd167e672 --- /dev/null +++ b/grails-doc/src/en/guide/upgrading/upgrading100x.adoc @@ -0,0 +1,80 @@ +//// +Licensed to the Apache Software Foundation (ASF) under one +or more contributor license agreements. See the NOTICE file +distributed with this work for additional information +regarding copyright ownership. The ASF licenses this file +to you under the Apache License, Version 2.0 (the +"License"); you may not use this file except in compliance +with the License. You may obtain a copy of the License at + +https://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, +software distributed under the License is distributed on an +"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, either express or implied. See the License for the +specific language governing permissions and limitations +under the License. +//// + +=== Upgrade Instructions for Grails 9 to Grails 10 + +This guide outlines the changes introduced in Grails 10 and the steps required to upgrade your application. + +==== 1. Opt Into Spring MVC Content Negotiation for Grails Formats + +Set `grails.mime.negotiation.spring: true` to resolve `request.format`, `response.format`, `withFormat` and the format +`respond` writes in with Spring MVC's content negotiation manager, and to have the `format` parameter, URL extensions and +the `grails.mime` settings of the `Accept` header decide what Spring MVC writes for an action too (see +<>). Grails 10 keeps the negotiation of +Grails 9 by default. + +[source,yaml] +.grails-app/conf/application.yml +---- +grails: + mime: + negotiation: + spring: true +---- + +The setting changes these answers, which the framework's tests record by running the same requests through both: + +* *The order of the `Accept` header.* Spring MVC takes a more specific type ahead of a less specific one of equal +quality, where Grails 9 kept the order of the header: `Accept: */*, application/json` is the `json` format, where it was +`all`, and `withFormat` runs the `json` block rather than its first. A type with the `+xml` suffix no longer comes ahead +of `application/xml`: `Accept: application/xml, application/atom+xml` is `xml`, where it was `atom`. +* *Types with the `+json` and `+xml` suffixes.* A type no configured type names, such as `application/merge-patch+json`, +`application/soap+xml` or, without a `hal` format, `application/hal+json`, is the `json` or `xml` format, where Grails 9 +read only the problem types of RFC 9457 so and answered any other as `all`. In `Content-Type` too: a body sent as such a +type is of the `json` format, where its `request.format` was `null`, and data binding reads it as JSON. +* *A request that accepts no configured type.* Such a request, as one that sends only `Accept: image/png`, and one whose +`Accept` header Spring cannot read, such as `Accept: application/json;q=abc`, is not acceptable: `response.format` and +`response.mimeType` are `null`, `respond` answers `406 Not Acceptable` and `withFormat` runs its `*` block, or no block, +where Grails 9 answered as for a client that accepts any type, with the `all` format, or read the header leniently. Code +that reads `response.format` or `response.mimeType` must allow for `null`. +* *The `format` parameter and URL extensions.* A format no type is configured for is not acceptable, to `respond`, which +answers `406`, and to what Spring MVC writes, where Grails 9 answered in the first configured format; `withFormat` +answers it from the `Accept` header, as for a format it has no block for. The `all` format leaves the format to the +`Accept` header: `?format=all` with `Accept: application/json` is `json`, where it was `all`. The first value of the +parameter counts. +* *What Spring MVC writes for an action.* The `format` parameter and URL extensions now decide the type of a +`ResponseEntity`, a `ProblemDetail` or another value Spring MVC writes for a request a URL mapping handles, where Spring +MVC read only the `Accept` header: `/book/show/1.json` is answered in JSON whatever the `Accept` header asks for, and +`/book/show/1.html` of an action that returns a map with `406`, since no message converter writes a map as HTML. +`grails.mime.use.accept.header: false` and `grails.mime.disable.accept.header.*` now ignore the `Accept` header for it +too. +* *Without the `all` format.* Where `grails.mime.types` does not list `all`, a request without an `Accept` header is of +the `all` format, as one that sends `Accept: */*` is, where Grails 9 gave the first configured format, so `withFormat` +runs its `*` block, or its first block, rather than the block of that format. A type of quality `0` comes after any +other, so `Accept: application/json;q=0, */*;q=0.1` is `all`, where it was `json`. `?format=all` is then an unknown +format. +* *Wildcards.* A wildcard such as `text/*` is the `all` format as before, but `withFormat` runs the first block of a +format with a type compatible with it, and `respond` answers in the first such format of the action, where Grails 9 ran +the first block and answered in the first format: `withFormat { pdf {...}; html {...} }` runs the `html` block for +`Accept: text/*`. +* *A `Content-Type` Spring cannot read.* A `Content-Type` Spring rejects, such as `application/json;charset=` or a list +of types, is of no format, where Grails 9 read it leniently as `json`. + +Other requests resolve as before, among them those of browsers and those that name one configured type. A Spring MVC +endpoint, and Spring Security's filters before a URL mapping has matched a request, negotiate as before. From c41b857df1d071ca580e6f989ef2d9b958bc7ba6 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Sat, 14 Nov 2026 12:13:46 -0800 Subject: [PATCH 07/21] Offer grails.mime.negotiation.spring from Grails 9 The setting is opt-in in Grails 9, and Grails 10 makes it the default, as it does for the other migration settings in grails.config.Settings: the new API is @since 9.0, the upgrade notes are section 22 of Upgrading from Grails 8 to Grails 9, which the content negotiation guide and What's New point to, and the settings documentation gives its default as false in Grails 9 and true from Grails 10. --- .../main/groovy/grails/config/Settings.groovy | 8 +- .../en/guide/conf/config/builtInOptions.adoc | 2 +- .../src/en/guide/introduction/whatsNew.adoc | 9 ++- .../guide/theWebLayer/contentNegotiation.adoc | 5 +- grails-doc/src/en/guide/toc.yml | 1 - .../src/en/guide/upgrading/upgrading100x.adoc | 80 ------------------- .../src/en/guide/upgrading/upgrading90x.adoc | 58 ++++++++++++++ .../web/api/MimeTypesApiSupport.groovy | 2 +- .../web/mime/MimeTypesConfiguration.groovy | 2 +- ...eptHeaderContentNegotiationStrategy.groovy | 2 +- .../GrailsContentNegotiationManager.groovy | 2 +- ...tentNegotiationManagerPostProcessor.groovy | 2 +- .../GrailsContentNegotiationStrategy.groovy | 22 ++--- ...ilsFormatContentNegotiationStrategy.groovy | 2 +- .../FormatNegotiationComparisonSpec.groovy | 2 +- ...itional-spring-configuration-metadata.json | 2 +- 16 files changed, 93 insertions(+), 108 deletions(-) delete mode 100644 grails-doc/src/en/guide/upgrading/upgrading100x.adoc diff --git a/grails-core/src/main/groovy/grails/config/Settings.groovy b/grails-core/src/main/groovy/grails/config/Settings.groovy index 339a6c75bac..86833775518 100644 --- a/grails-core/src/main/groovy/grails/config/Settings.groovy +++ b/grails-core/src/main/groovy/grails/config/Settings.groovy @@ -218,15 +218,15 @@ interface Settings { * Grails keeps to what Spring MVC writes for the requests a URL mapping handles, rather than by Grails' own rules. * Defaults to {@link #MIME_NEGOTIATION_SPRING_DEFAULT}. * - * @since 10.0 + * @since 9.0 */ String MIME_NEGOTIATION_SPRING = 'grails.mime.negotiation.spring' /** - * The default of {@link #MIME_NEGOTIATION_SPRING}, as a property placeholder reads it: {@code false} in Grails 10, - * which keeps the negotiation of Grails 9. + * The default of {@link #MIME_NEGOTIATION_SPRING}, as a property placeholder reads it: {@code false} in Grails 9, + * and {@code true} from Grails 10. * - * @since 10.0 + * @since 9.0 */ String MIME_NEGOTIATION_SPRING_DEFAULT = 'false' diff --git a/grails-doc/src/en/guide/conf/config/builtInOptions.adoc b/grails-doc/src/en/guide/conf/config/builtInOptions.adoc index 7828aba7588..e82d11c9b73 100644 --- a/grails-doc/src/en/guide/conf/config/builtInOptions.adoc +++ b/grails-doc/src/en/guide/conf/config/builtInOptions.adoc @@ -34,7 +34,7 @@ On the runtime front, i.e. `grails-app/conf/application.yml`, there are quite a * `grails.views.gsp.encoding` - The file encoding used for GSP source files (default: 'utf-8'). * `grails.mime.file.extensions` - Whether to use the file extension to dictate the mime type in link:theWebLayer.html#contentNegotiation[Content Negotiation] (default: true). * `grails.mime.types` - A map of supported mime types used for link:theWebLayer.html#contentNegotiation[Content Negotiation]. -* `grails.mime.negotiation.spring` - Whether `request.format`, `response.format`, `withFormat` and the format `respond` writes in are resolved with Spring MVC's content negotiation manager, as the formats `grails.mime.types` gives the media types it resolves, rather than by the Grails rules; the `format` parameter, URL extensions and the `grails.mime` settings of the `Accept` header then also decide what Spring MVC writes for an action (default: false). See <>. +* `grails.mime.negotiation.spring` - Whether `request.format`, `response.format`, `withFormat` and the format `respond` writes in are resolved with Spring MVC's content negotiation manager, as the formats `grails.mime.types` gives the media types it resolves, rather than by the Grails rules; the `format` parameter, URL extensions and the `grails.mime` settings of the `Accept` header then also decide what Spring MVC writes for an action (default: false; true from Grails 10). See <>. * `grails.serverURL` - A string specifying the server URL portion of absolute links, including server name e.g. grails.serverURL="https://my.yourportal.com". See link:{gspTagsRef}createLink.html[createLink]. Also used by redirects. * `grails.views.gsp.layout.preprocess` - Determines whether layout preprocessing happens. Disabling this slows down page rendering, but if you need Grails' layout implementation to parse the generated HTML from a GSP view, then disabling it is the right option. Don't worry if you don't understand this advanced property: leave it set to true. * `grails.reload.excludes` and `grails.reload.includes` - Configuring these directives determines the reload behavior for project specific source files. Each directive takes a list of strings that are the class names for project source files that should be excluded from reloading behavior or included accordingly when running the application in development with the `bootRun` task. If the `grails.reload.includes` directive is configured, then only the classes in that list will be reloaded. diff --git a/grails-doc/src/en/guide/introduction/whatsNew.adoc b/grails-doc/src/en/guide/introduction/whatsNew.adoc index f74ffae4ba4..d2ecf56847a 100644 --- a/grails-doc/src/en/guide/introduction/whatsNew.adoc +++ b/grails-doc/src/en/guide/introduction/whatsNew.adoc @@ -134,7 +134,14 @@ an action annotated `@ResponseBody`, a `CompletableFuture` it returns included. selects the properties `respond` writes through Spring MVC. See xref:theWebLayer#springResponses[Returning Spring MVC Responses]. -See xref:upgrading#upgrading90x[Upgrading from Grails 8 to Grails 9], sections 4 to 11 and 13 to 16. +With `grails.mime.negotiation.spring: true`, which Grails 10 makes the default, `request.format`, `response.format`, +`withFormat` and the format `respond` writes in are resolved with Spring MVC's content negotiation manager, so that the +`spring.mvc.contentnegotiation.*` settings apply to them, and the `format` parameter, URL extensions and the +`grails.mime` settings of the `Accept` header decide what Spring MVC writes for an action too, such as a +`ResponseEntity` it returns. See xref:theWebLayer#springFormatNegotiation[Resolving Formats with Spring MVC Content +Negotiation]. + +See xref:upgrading#upgrading90x[Upgrading from Grails 8 to Grails 9], sections 4 to 11, 13 to 16 and 22. ==== Hibernate 7 Criteria Queries Can Be Extended diff --git a/grails-doc/src/en/guide/theWebLayer/contentNegotiation.adoc b/grails-doc/src/en/guide/theWebLayer/contentNegotiation.adoc index 797b16a7ba5..6aee23a57d9 100644 --- a/grails-doc/src/en/guide/theWebLayer/contentNegotiation.adoc +++ b/grails-doc/src/en/guide/theWebLayer/contentNegotiation.adoc @@ -282,7 +282,8 @@ grails: spring: true ---- -Grails {grailsMajorVersion} keeps the Grails rules by default. With the setting: +Grails {grailsMajorVersion} keeps the Grails rules by default, and Grails 10 makes the setting the default. With the +setting: * The `Accept` header is read by Spring MVC's manager, with its strategies, so the `spring.mvc.contentnegotiation.*` properties apply to the Grails formats as they do to Spring MVC, and its media types are taken in the order Spring MVC @@ -342,7 +343,7 @@ type is configured for in the first configured format |Dropped: such a request, and one whose `Accept` header Spring cannot read, is not acceptable. |=== -See xref:upgrading#upgrading100x[Upgrading from Grails 9 to Grails 10] for how each answer changes. +Section 22 of xref:upgrading#upgrading90x[Upgrading from Grails 8 to Grails 9] lists how each answer changes. ==== Testing Content Negotiation diff --git a/grails-doc/src/en/guide/toc.yml b/grails-doc/src/en/guide/toc.yml index 6d49075f174..25fe7b73d95 100644 --- a/grails-doc/src/en/guide/toc.yml +++ b/grails-doc/src/en/guide/toc.yml @@ -37,7 +37,6 @@ gettingStarted: developmentReloading: Development Reloading upgrading: title: Upgrading from the previous versions - upgrading100x: Upgrading from Grails 9 to Grails 10 upgrading90x: Upgrading from Grails 8 to Grails 9 upgrading81x: Upgrading from Grails 8.0 to Grails 8.1 upgrading80x: Upgrading from Grails 7 to Grails 8 diff --git a/grails-doc/src/en/guide/upgrading/upgrading100x.adoc b/grails-doc/src/en/guide/upgrading/upgrading100x.adoc deleted file mode 100644 index eecd167e672..00000000000 --- a/grails-doc/src/en/guide/upgrading/upgrading100x.adoc +++ /dev/null @@ -1,80 +0,0 @@ -//// -Licensed to the Apache Software Foundation (ASF) under one -or more contributor license agreements. See the NOTICE file -distributed with this work for additional information -regarding copyright ownership. The ASF licenses this file -to you under the Apache License, Version 2.0 (the -"License"); you may not use this file except in compliance -with the License. You may obtain a copy of the License at - -https://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, -software distributed under the License is distributed on an -"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -KIND, either express or implied. See the License for the -specific language governing permissions and limitations -under the License. -//// - -=== Upgrade Instructions for Grails 9 to Grails 10 - -This guide outlines the changes introduced in Grails 10 and the steps required to upgrade your application. - -==== 1. Opt Into Spring MVC Content Negotiation for Grails Formats - -Set `grails.mime.negotiation.spring: true` to resolve `request.format`, `response.format`, `withFormat` and the format -`respond` writes in with Spring MVC's content negotiation manager, and to have the `format` parameter, URL extensions and -the `grails.mime` settings of the `Accept` header decide what Spring MVC writes for an action too (see -<>). Grails 10 keeps the negotiation of -Grails 9 by default. - -[source,yaml] -.grails-app/conf/application.yml ----- -grails: - mime: - negotiation: - spring: true ----- - -The setting changes these answers, which the framework's tests record by running the same requests through both: - -* *The order of the `Accept` header.* Spring MVC takes a more specific type ahead of a less specific one of equal -quality, where Grails 9 kept the order of the header: `Accept: */*, application/json` is the `json` format, where it was -`all`, and `withFormat` runs the `json` block rather than its first. A type with the `+xml` suffix no longer comes ahead -of `application/xml`: `Accept: application/xml, application/atom+xml` is `xml`, where it was `atom`. -* *Types with the `+json` and `+xml` suffixes.* A type no configured type names, such as `application/merge-patch+json`, -`application/soap+xml` or, without a `hal` format, `application/hal+json`, is the `json` or `xml` format, where Grails 9 -read only the problem types of RFC 9457 so and answered any other as `all`. In `Content-Type` too: a body sent as such a -type is of the `json` format, where its `request.format` was `null`, and data binding reads it as JSON. -* *A request that accepts no configured type.* Such a request, as one that sends only `Accept: image/png`, and one whose -`Accept` header Spring cannot read, such as `Accept: application/json;q=abc`, is not acceptable: `response.format` and -`response.mimeType` are `null`, `respond` answers `406 Not Acceptable` and `withFormat` runs its `*` block, or no block, -where Grails 9 answered as for a client that accepts any type, with the `all` format, or read the header leniently. Code -that reads `response.format` or `response.mimeType` must allow for `null`. -* *The `format` parameter and URL extensions.* A format no type is configured for is not acceptable, to `respond`, which -answers `406`, and to what Spring MVC writes, where Grails 9 answered in the first configured format; `withFormat` -answers it from the `Accept` header, as for a format it has no block for. The `all` format leaves the format to the -`Accept` header: `?format=all` with `Accept: application/json` is `json`, where it was `all`. The first value of the -parameter counts. -* *What Spring MVC writes for an action.* The `format` parameter and URL extensions now decide the type of a -`ResponseEntity`, a `ProblemDetail` or another value Spring MVC writes for a request a URL mapping handles, where Spring -MVC read only the `Accept` header: `/book/show/1.json` is answered in JSON whatever the `Accept` header asks for, and -`/book/show/1.html` of an action that returns a map with `406`, since no message converter writes a map as HTML. -`grails.mime.use.accept.header: false` and `grails.mime.disable.accept.header.*` now ignore the `Accept` header for it -too. -* *Without the `all` format.* Where `grails.mime.types` does not list `all`, a request without an `Accept` header is of -the `all` format, as one that sends `Accept: */*` is, where Grails 9 gave the first configured format, so `withFormat` -runs its `*` block, or its first block, rather than the block of that format. A type of quality `0` comes after any -other, so `Accept: application/json;q=0, */*;q=0.1` is `all`, where it was `json`. `?format=all` is then an unknown -format. -* *Wildcards.* A wildcard such as `text/*` is the `all` format as before, but `withFormat` runs the first block of a -format with a type compatible with it, and `respond` answers in the first such format of the action, where Grails 9 ran -the first block and answered in the first format: `withFormat { pdf {...}; html {...} }` runs the `html` block for -`Accept: text/*`. -* *A `Content-Type` Spring cannot read.* A `Content-Type` Spring rejects, such as `application/json;charset=` or a list -of types, is of no format, where Grails 9 read it leniently as `json`. - -Other requests resolve as before, among them those of browsers and those that name one configured type. A Spring MVC -endpoint, and Spring Security's filters before a URL mapping has matched a request, negotiate as before. diff --git a/grails-doc/src/en/guide/upgrading/upgrading90x.adoc b/grails-doc/src/en/guide/upgrading/upgrading90x.adoc index 9b4cb68887c..dad7baaca1e 100644 --- a/grails-doc/src/en/guide/upgrading/upgrading90x.adoc +++ b/grails-doc/src/en/guide/upgrading/upgrading90x.adoc @@ -1274,3 +1274,61 @@ A property source of lower precedence that sets the deeper key now answers it. W * Code that reads a child of a string or a closure and relied on being answered with the parent reads the parent instead. * Code that read a whole list through a key ending in a whole number, such as `server.ports.0`, now gets the element; it reads the list as `server.ports`. * A typed read with a default below such a value, such as `getProperty('x.y.enabled', Boolean, true)` when `x.y` is `false`, reads the parent, or the configuration sets the deeper key. + +==== 22. Opt Into Spring MVC Content Negotiation for Grails Formats + +Set `grails.mime.negotiation.spring: true` to resolve `request.format`, `response.format`, `withFormat` and the format +`respond` writes in with Spring MVC's content negotiation manager, and to have the `format` parameter, URL extensions and +the `grails.mime` settings of the `Accept` header decide what Spring MVC writes for an action too (see +<>). Grails 9 keeps its own rules by +default, and Grails 10 makes the setting the default, so an application should check these answers before then. + +[source,yaml] +.grails-app/conf/application.yml +---- +grails: + mime: + negotiation: + spring: true +---- + +The setting changes these answers, which the framework's tests record by running the same requests both ways: + +* *The order of the `Accept` header.* Spring MVC takes a more specific type ahead of a less specific one of equal +quality, where the Grails rules keep the order of the header: `Accept: */*, application/json` is the `json` format, +where it is `all` without the setting, and `withFormat` runs the `json` block rather than its first. A type with the `+xml` suffix no longer comes ahead +of `application/xml`: `Accept: application/xml, application/atom+xml` is `xml`, where it is `atom` without the setting. +* *Types with the `+json` and `+xml` suffixes.* A type no configured type names, such as `application/merge-patch+json`, +`application/soap+xml` or, without a `hal` format, `application/hal+json`, is the `json` or `xml` format, where the +Grails rules read only the problem types of RFC 9457 so and answer any other as `all`. In `Content-Type` too: a body sent +as such a type is of the `json` format, where its `request.format` is otherwise `null`, and data binding reads it as JSON. +* *A request that accepts no configured type.* Such a request, as one that sends only `Accept: image/png`, and one whose +`Accept` header Spring cannot read, such as `Accept: application/json;q=abc`, is not acceptable: `response.format` and +`response.mimeType` are `null`, `respond` answers `406 Not Acceptable` and `withFormat` runs its `*` block, or no block, +where the Grails rules answer as for a client that accepts any type, with the `all` format, or read the header +leniently. Code that reads `response.format` or `response.mimeType` must allow for `null`. +* *The `format` parameter and URL extensions.* A format no type is configured for is not acceptable, to `respond`, which +answers `406`, and to what Spring MVC writes, where the Grails rules answer in the first configured format; +`withFormat` answers it from the `Accept` header, as for a format it has no block for. The `all` format leaves the +format to the `Accept` header: `?format=all` with `Accept: application/json` is `json`, where it is otherwise `all`. The +first value of the parameter counts. +* *What Spring MVC writes for an action.* The `format` parameter and URL extensions now decide the type of a +`ResponseEntity`, a `ProblemDetail` or another value Spring MVC writes for a request a URL mapping handles, where Spring +MVC read only the `Accept` header: `/book/show/1.json` is answered in JSON whatever the `Accept` header asks for, and +`/book/show/1.html` of an action that returns a map with `406`, since no message converter writes a map as HTML. +`grails.mime.use.accept.header: false` and `grails.mime.disable.accept.header.*` now ignore the `Accept` header for it +too. +* *Without the `all` format.* Where `grails.mime.types` does not list `all`, a request without an `Accept` header is of +the `all` format, as one that sends `Accept: */*` is, where the Grails rules give the first configured format, so +`withFormat` runs its `*` block, or its first block, rather than the block of that format. A type of quality `0` comes +after any other, so `Accept: application/json;q=0, */*;q=0.1` is `all`, where it is otherwise `json`. `?format=all` is +then an unknown format. +* *Wildcards.* A wildcard such as `text/*` is the `all` format as before, but `withFormat` runs the first block of a +format with a type compatible with it, and `respond` answers in the first such format of the action, where the Grails +rules run the first block and answer in the first format: `withFormat { pdf {...}; html {...} }` runs the `html` block for +`Accept: text/*`. +* *A `Content-Type` Spring cannot read.* A `Content-Type` Spring rejects, such as `application/json;charset=` or a list +of types, is of no format, where the Grails rules read it leniently as `json`. + +Other requests resolve as before, among them those of browsers and those that name one configured type. A Spring MVC +endpoint, and Spring Security's filters before a URL mapping has matched a request, negotiate as before. diff --git a/grails-mimetypes/src/main/groovy/org/grails/plugins/web/api/MimeTypesApiSupport.groovy b/grails-mimetypes/src/main/groovy/org/grails/plugins/web/api/MimeTypesApiSupport.groovy index 378032de564..0fd8470a2ea 100644 --- a/grails-mimetypes/src/main/groovy/org/grails/plugins/web/api/MimeTypesApiSupport.groovy +++ b/grails-mimetypes/src/main/groovy/org/grails/plugins/web/api/MimeTypesApiSupport.groovy @@ -125,7 +125,7 @@ class MimeTypesApiSupport { * @param formats the blocks, by format * @param accepted the type of the {@code all} format * @return the result of the block, or {@link #NO_FORMAT} where none is of a format compatible with the wildcard - * @since 10.0 + * @since 9.0 */ protected Object resolveAllFormat(formatProvider, LinkedHashMap formats, MimeType accepted) { if (accepted == null || accepted.extension != 'all' || accepted.name == MimeType.ALL.name || formats.containsKey('*')) { diff --git a/grails-mimetypes/src/main/groovy/org/grails/plugins/web/mime/MimeTypesConfiguration.groovy b/grails-mimetypes/src/main/groovy/org/grails/plugins/web/mime/MimeTypesConfiguration.groovy index c336b6f884a..d5393f65d9b 100644 --- a/grails-mimetypes/src/main/groovy/org/grails/plugins/web/mime/MimeTypesConfiguration.groovy +++ b/grails-mimetypes/src/main/groovy/org/grails/plugins/web/mime/MimeTypesConfiguration.groovy @@ -174,7 +174,7 @@ class MimeTypesConfiguration { * created before the other beans, and the strategy it applies them with is that of the configurer, once a request * is negotiated. * - * @since 10.0 + * @since 9.0 */ @Bean static GrailsContentNegotiationManagerPostProcessor grailsContentNegotiationManagerPostProcessor( diff --git a/grails-mimetypes/src/main/groovy/org/grails/web/mime/GrailsAcceptHeaderContentNegotiationStrategy.groovy b/grails-mimetypes/src/main/groovy/org/grails/web/mime/GrailsAcceptHeaderContentNegotiationStrategy.groovy index 6edfed24860..acbd45f240b 100644 --- a/grails-mimetypes/src/main/groovy/org/grails/web/mime/GrailsAcceptHeaderContentNegotiationStrategy.groovy +++ b/grails-mimetypes/src/main/groovy/org/grails/web/mime/GrailsAcceptHeaderContentNegotiationStrategy.groovy @@ -36,7 +36,7 @@ import org.springframework.web.context.request.NativeWebRequest * resolves for it. Any other request, such as one a Spring MVC endpoint handles, is negotiated by the strategy it * replaces. It is a {@link HeaderContentNegotiationStrategy}, so that it is found as Spring MVC's is. * - * @since 10.0 + * @since 9.0 */ @CompileStatic class GrailsAcceptHeaderContentNegotiationStrategy extends HeaderContentNegotiationStrategy { diff --git a/grails-mimetypes/src/main/groovy/org/grails/web/mime/GrailsContentNegotiationManager.groovy b/grails-mimetypes/src/main/groovy/org/grails/web/mime/GrailsContentNegotiationManager.groovy index 6c8aa49dba6..7a0cc525577 100644 --- a/grails-mimetypes/src/main/groovy/org/grails/web/mime/GrailsContentNegotiationManager.groovy +++ b/grails-mimetypes/src/main/groovy/org/grails/web/mime/GrailsContentNegotiationManager.groovy @@ -34,7 +34,7 @@ import org.springframework.web.accept.MediaTypeFileExtensionResolver * ignores it for such a request where the {@code grails.mime} settings say so. Any other request is negotiated as by * Spring MVC's manager, whose formats and file extensions it answers with. * - * @since 10.0 + * @since 9.0 */ @CompileStatic class GrailsContentNegotiationManager extends ContentNegotiationManager { diff --git a/grails-mimetypes/src/main/groovy/org/grails/web/mime/GrailsContentNegotiationManagerPostProcessor.groovy b/grails-mimetypes/src/main/groovy/org/grails/web/mime/GrailsContentNegotiationManagerPostProcessor.groovy index 2299b6d562d..463c60e50f3 100644 --- a/grails-mimetypes/src/main/groovy/org/grails/web/mime/GrailsContentNegotiationManagerPostProcessor.groovy +++ b/grails-mimetypes/src/main/groovy/org/grails/web/mime/GrailsContentNegotiationManagerPostProcessor.groovy @@ -36,7 +36,7 @@ import grails.config.Settings * a {@code ProblemDetail} an action returns or {@code respond} writes, is negotiated as Grails resolves their formats. * Without it, Spring MVC's manager is left as it is. * - * @since 10.0 + * @since 9.0 */ @CompileStatic class GrailsContentNegotiationManagerPostProcessor implements BeanPostProcessor { diff --git a/grails-mimetypes/src/main/groovy/org/grails/web/mime/GrailsContentNegotiationStrategy.groovy b/grails-mimetypes/src/main/groovy/org/grails/web/mime/GrailsContentNegotiationStrategy.groovy index 68a18d7a4ec..54c7226b527 100644 --- a/grails-mimetypes/src/main/groovy/org/grails/web/mime/GrailsContentNegotiationStrategy.groovy +++ b/grails-mimetypes/src/main/groovy/org/grails/web/mime/GrailsContentNegotiationStrategy.groovy @@ -94,7 +94,7 @@ class GrailsContentNegotiationStrategy { * {@code grails.mime.negotiation.spring}, the formats are resolved with; asked for each request, since the * strategy is created before it; or {@code null}, or one that supplies none, for one that reads the * {@code Accept} header alone, as Spring MVC's default does - * @since 10.0 + * @since 9.0 */ GrailsContentNegotiationStrategy(MimeType[] mimeTypes, Config config, Supplier contentNegotiationManager) { @@ -123,7 +123,7 @@ class GrailsContentNegotiationStrategy { /** * @return whether the formats are resolved with Spring MVC's content negotiation manager, as * {@code grails.mime.negotiation.spring} says - * @since 10.0 + * @since 9.0 */ boolean isSpringNegotiation() { return springNegotiation @@ -160,7 +160,7 @@ class GrailsContentNegotiationStrategy { * @return its first configured type; for a format that is not configured, the first configured type, as Grails 9 * answers, or, with {@code grails.mime.negotiation.spring}, {@code null}, since the request accepts no * configured type - * @since 10.0 + * @since 9.0 */ MimeType resolveFormat(Object format) { MimeType mimeType = mimeTypes.find { MimeType configured -> configured.extension == format } @@ -178,7 +178,7 @@ class GrailsContentNegotiationStrategy { * * @param webRequest the request * @return the format, or {@code null} where the request names none - * @since 10.0 + * @since 9.0 */ Object requestedFormat(GrailsWebRequest webRequest) { Object format = webRequest?.params?.get(FORMAT_PARAMETER) @@ -202,7 +202,7 @@ class GrailsContentNegotiationStrategy { * * @param request the request * @return the MIME types of its content - * @since 10.0 + * @since 9.0 */ MimeType[] resolveContentMimeTypes(HttpServletRequest request) { String header = request.contentType ?: request.getHeader(HttpHeaders.CONTENT_TYPE) @@ -230,7 +230,7 @@ class GrailsContentNegotiationStrategy { * * @param format the format * @return the media types, or {@code null} where no type of the format is configured - * @since 10.0 + * @since 9.0 */ List mediaTypesOf(String format) { List types = [] @@ -254,7 +254,7 @@ class GrailsContentNegotiationStrategy { /** * @return the media types of every configured MIME type Spring can read, which a request that names a format no type * is configured for is not acceptable in - * @since 10.0 + * @since 9.0 */ List getConfiguredMediaTypes() { return mediaTypes.findAll { it }.unique() as List @@ -263,7 +263,7 @@ class GrailsContentNegotiationStrategy { /** * @return whether the {@code Accept} header of a request is ignored, as {@code grails.mime.use.accept.header} and * {@code grails.mime.disable.accept.header.*} say - * @since 10.0 + * @since 9.0 */ boolean ignoresAcceptHeader(HttpServletRequest request) { if (!useAcceptHeader) { @@ -284,7 +284,7 @@ class GrailsContentNegotiationStrategy { * * @param request the request * @return whether a URL mapping handles it - * @since 10.0 + * @since 9.0 */ static boolean handlesRequest(HttpServletRequest request) { return request.getAttribute(HandlerMapping.BEST_MATCHING_HANDLER_ATTRIBUTE) instanceof UrlMappingInfo @@ -297,7 +297,7 @@ class GrailsContentNegotiationStrategy { * * @param request the request * @return the strategy - * @since 10.0 + * @since 9.0 */ static GrailsContentNegotiationStrategy forRequest(HttpServletRequest request) { ApplicationContext applicationContext = GrailsWebRequest.lookup()?.applicationContext @@ -387,7 +387,7 @@ class GrailsContentNegotiationStrategy { * @param accepted a type {@code response.mimeTypes} resolves * @param format a format * @return whether it accepts the format - * @since 10.0 + * @since 9.0 */ boolean acceptsFormat(MimeType accepted, String format) { if (accepted == null) { diff --git a/grails-mimetypes/src/main/groovy/org/grails/web/mime/GrailsFormatContentNegotiationStrategy.groovy b/grails-mimetypes/src/main/groovy/org/grails/web/mime/GrailsFormatContentNegotiationStrategy.groovy index b5e15c878ed..9db039048b1 100644 --- a/grails-mimetypes/src/main/groovy/org/grails/web/mime/GrailsFormatContentNegotiationStrategy.groovy +++ b/grails-mimetypes/src/main/groovy/org/grails/web/mime/GrailsFormatContentNegotiationStrategy.groovy @@ -38,7 +38,7 @@ import org.grails.web.servlet.mvc.GrailsWebRequest * leaves any other request, such as one a Spring MVC endpoint handles, to them, and so a request whose format names no * type, as the {@code all} format does. A request that names a format no type is configured for is not acceptable. * - * @since 10.0 + * @since 9.0 */ @CompileStatic class GrailsFormatContentNegotiationStrategy implements ContentNegotiationStrategy { diff --git a/grails-mimetypes/src/test/groovy/org/grails/web/mime/FormatNegotiationComparisonSpec.groovy b/grails-mimetypes/src/test/groovy/org/grails/web/mime/FormatNegotiationComparisonSpec.groovy index 8ec724d1d45..7c5e63e836b 100644 --- a/grails-mimetypes/src/test/groovy/org/grails/web/mime/FormatNegotiationComparisonSpec.groovy +++ b/grails-mimetypes/src/test/groovy/org/grails/web/mime/FormatNegotiationComparisonSpec.groovy @@ -140,7 +140,7 @@ class FormatNegotiationComparisonSpec extends Specification { [contentType: 'image/png'] ] - /** Every answer that differs, as {@code configuration | request | answer: Grails 9 -> Spring}. */ + /** Every answer that differs, as {@code configuration | request | answer: Grails rules -> Spring MVC's}. */ private static final List RECORDED = [ 'defaults | Accept: */*, application/json | response.format: all -> json', 'defaults | Accept: */*, application/json | withFormat(html, json, xml): html -> json', diff --git a/grails-web-core/src/main/resources/META-INF/additional-spring-configuration-metadata.json b/grails-web-core/src/main/resources/META-INF/additional-spring-configuration-metadata.json index 7a236c80de6..c3842951ce1 100644 --- a/grails-web-core/src/main/resources/META-INF/additional-spring-configuration-metadata.json +++ b/grails-web-core/src/main/resources/META-INF/additional-spring-configuration-metadata.json @@ -135,7 +135,7 @@ { "name": "grails.mime.negotiation.spring", "type": "java.lang.Boolean", - "description": "Whether request.format, response.format, withFormat and the format respond writes in are resolved with Spring MVC's content negotiation manager, mapping the media types it resolves to the formats grails.mime.types gives them, rather than by the Grails rules. The format parameter, URL extensions and the grails.mime Accept header settings are kept, as strategies of Spring MVC's manager that also apply to what Spring MVC writes for the requests a URL mapping handles. Grails 9 negotiation stays the default in Grails 10.", + "description": "Whether request.format, response.format, withFormat and the format respond writes in are resolved with Spring MVC's content negotiation manager, mapping the media types it resolves to the formats grails.mime.types gives them, rather than by the Grails rules. The format parameter, URL extensions and the grails.mime Accept header settings are kept, as strategies of Spring MVC's manager that also apply to what Spring MVC writes for the requests a URL mapping handles. Grails 10 makes it the default.", "defaultValue": false }, { From 915151f3ffd78cf7a316face82f6d10c82c913f6 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Sat, 14 Nov 2026 12:18:01 -0800 Subject: [PATCH 08/21] Match a Spring MVC endpoint an action forwards to on its own negotiation A forward an action makes is a dispatch of its own, which Spring MVC's handler mappings match after the URL mappings, while the mapping of the forwarding dispatch was still the request's best matching handler. With grails.mime.negotiation.spring, the produces condition of an endpoint was then matched on the format the action was asked for: /book/forward?format=xml to an endpoint that produces JSON answered 406 for a client that accepts JSON. The URL mappings now take a mapping an earlier dispatch left off the request when they match no handler for the dispatch. --- .../contentneg/SpringWrittenController.groovy | 4 ++++ .../SpringFormatNegotiationSpec.groovy | 9 +++++++-- .../contentneg/SpringNegotiationApi.groovy | 2 +- .../mvc/UrlMappingsHandlerMapping.groovy | 5 +++++ .../mvc/UrlMappingsHandlerMappingSpec.groovy | 20 +++++++++++++++++++ 5 files changed, 37 insertions(+), 3 deletions(-) diff --git a/grails-test-examples/app1/grails-app/controllers/functionaltests/contentneg/SpringWrittenController.groovy b/grails-test-examples/app1/grails-app/controllers/functionaltests/contentneg/SpringWrittenController.groovy index a07bf04f2b2..06398002916 100644 --- a/grails-test-examples/app1/grails-app/controllers/functionaltests/contentneg/SpringWrittenController.groovy +++ b/grails-test-examples/app1/grails-app/controllers/functionaltests/contentneg/SpringWrittenController.groovy @@ -37,4 +37,8 @@ class SpringWrittenController { def formats() { render(contentType: 'text/plain', text: "${response.format}|${request.format}") } + + def forwardToSpring() { + forward(uri: '/springNegotiation') + } } diff --git a/grails-test-examples/app1/src/integration-test/groovy/functionaltests/contentneg/SpringFormatNegotiationSpec.groovy b/grails-test-examples/app1/src/integration-test/groovy/functionaltests/contentneg/SpringFormatNegotiationSpec.groovy index e7f691c56fd..7bdea2c334e 100644 --- a/grails-test-examples/app1/src/integration-test/groovy/functionaltests/contentneg/SpringFormatNegotiationSpec.groovy +++ b/grails-test-examples/app1/src/integration-test/groovy/functionaltests/contentneg/SpringFormatNegotiationSpec.groovy @@ -73,10 +73,15 @@ class SpringFormatNegotiationSpec extends Specification implements HttpClientSup http("/springNegotiation${query}", Accept: accept).assertStatus(status) where: - description | query | accept || status - 'the format parameter is ignored' | '?format=xml' | 'application/json' || 200 + description | query | accept || status + 'the format parameter is ignored' | '?format=xml' | 'application/json' || 200 'an unknown type is not acceptable' | '' | 'image/png' || 406 } + + void 'a Spring MVC endpoint an action forwards to is matched on the Accept header, not on the format the action was asked for'() { + expect: + http('/springWritten/forwardToSpring?format=xml', Accept: 'application/json').assertStatus(200).assertJson([title: 'Grails']) + } } /** diff --git a/grails-test-examples/app1/src/main/groovy/functionaltests/contentneg/SpringNegotiationApi.groovy b/grails-test-examples/app1/src/main/groovy/functionaltests/contentneg/SpringNegotiationApi.groovy index e50b73ae05c..cdfbc687039 100644 --- a/grails-test-examples/app1/src/main/groovy/functionaltests/contentneg/SpringNegotiationApi.groovy +++ b/grails-test-examples/app1/src/main/groovy/functionaltests/contentneg/SpringNegotiationApi.groovy @@ -28,7 +28,7 @@ import org.springframework.web.bind.annotation.RestController @RestController class SpringNegotiationApi { - @GetMapping('/springNegotiation') + @GetMapping(path = '/springNegotiation', produces = 'application/json') Map negotiation() { [title: 'Grails'] } diff --git a/grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMapping.groovy b/grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMapping.groovy index a4a673b371a..617b7983e96 100644 --- a/grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMapping.groovy +++ b/grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMapping.groovy @@ -193,6 +193,11 @@ class UrlMappingsHandlerMapping extends AbstractHandlerMapping { if (handler != null) { request.setAttribute(BEST_MATCHING_HANDLER_ATTRIBUTE, handler) } + else if (request.getAttribute(BEST_MATCHING_HANDLER_ATTRIBUTE) instanceof UrlMappingInfo) { + // A dispatch no mapping handles, such as a forward an action makes to a Spring MVC endpoint, is not handled by + // the mapping of the dispatch that made it, whose attribute the handler mapping that matches it reads first + request.removeAttribute(BEST_MATCHING_HANDLER_ATTRIBUTE) + } return handler } diff --git a/grails-web-url-mappings/src/test/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMappingSpec.groovy b/grails-web-url-mappings/src/test/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMappingSpec.groovy index 72233cada8b..85cbaeb2826 100644 --- a/grails-web-url-mappings/src/test/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMappingSpec.groovy +++ b/grails-web-url-mappings/src/test/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMappingSpec.groovy @@ -738,6 +738,26 @@ class UrlMappingsHandlerMappingSpec extends AbstractUrlMappingsSpec { request.getAttribute(HandlerMapping.BEST_MATCHING_HANDLER_ATTRIBUTE).is(springHandler) } + void 'a forward no mapping matches is no longer handled by the mapping of the dispatch that made it'() { + given: + def grailsApplication = new DefaultGrailsApplication(FooController) + grailsApplication.initialise() + def handler = new UrlMappingsHandlerMapping(new GrailsControllerUrlMappings(grailsApplication, getUrlMappingsHolder { + '/foo/bar'(controller: 'foo', action: 'bar') + })) + def request = GrailsWebMockUtil.bindMockWebRequest().request + request.requestURI = '/foo/bar' + handler.getHandler(request) + + when: 'the action forwards to a URI that a handler mapping of Spring MVC, which comes later, handles' + request.setAttribute(WebUtils.FORWARD_REQUEST_URI_ATTRIBUTE, '/foo/bar') + request.requestURI = '/spring/endpoint' + + then: + handler.getHandler(request) == null + request.getAttribute(HandlerMapping.BEST_MATCHING_HANDLER_ATTRIBUTE) == null + } + void 'a request no mapping matches keeps the best matching handler another handler mapping set'() { given: def handler = new UrlMappingsHandlerMapping(getUrlMappingsHolder { From a13c4890555c440dc0c327ba143683ecc6f5c93e Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Sat, 14 Nov 2026 12:39:26 -0800 Subject: [PATCH 09/21] Read grails.mime.negotiation.spring from the Grails configuration only The post-processor that replaces Spring MVC's content negotiation manager read the setting from the Spring Environment, while the strategy that resolves Grails formats read it from the application's configuration. A configuration that is not the environment, as one a test builds by hand or one code changes, could then enable one half of the setting without the other: Grails formats resolved with Spring MVC's manager while what Spring MVC writes ignored the Grails rules, or the other way round. Both now read the application's configuration. --- .../web/mime/MimeTypesConfiguration.groovy | 11 ++--- ...tentNegotiationManagerPostProcessor.groovy | 16 ++++--- .../mime/SpringFormatNegotiationSpec.groovy | 44 +++++++++++++++++++ 3 files changed, 59 insertions(+), 12 deletions(-) diff --git a/grails-mimetypes/src/main/groovy/org/grails/plugins/web/mime/MimeTypesConfiguration.groovy b/grails-mimetypes/src/main/groovy/org/grails/plugins/web/mime/MimeTypesConfiguration.groovy index d5393f65d9b..ec2be2c831e 100644 --- a/grails-mimetypes/src/main/groovy/org/grails/plugins/web/mime/MimeTypesConfiguration.groovy +++ b/grails-mimetypes/src/main/groovy/org/grails/plugins/web/mime/MimeTypesConfiguration.groovy @@ -28,7 +28,6 @@ import org.springframework.beans.factory.annotation.Qualifier import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.context.annotation.Primary -import org.springframework.core.env.Environment import org.springframework.web.accept.ContentNegotiationManager import grails.config.Config @@ -171,15 +170,17 @@ class MimeTypesConfiguration { /** * With {@code grails.mime.negotiation.spring}, has Spring MVC's content negotiation manager apply the * {@code grails.mime} rules Grails keeps to the requests a URL mapping handles. Static, as a post-processor is - * created before the other beans, and the strategy it applies them with is that of the configurer, once a request - * is negotiated. + * created before the other beans: it reads the setting from the application's configuration as Spring MVC's manager + * is created, as the strategy of the configurer, which it applies the rules with once a request is negotiated, reads + * it. * * @since 9.0 */ @Bean static GrailsContentNegotiationManagerPostProcessor grailsContentNegotiationManagerPostProcessor( - Environment environment, ObjectProvider grailsMimeTypesWebMvcConfigurer) { - return new GrailsContentNegotiationManagerPostProcessor(environment, () -> + ObjectProvider grailsApplication, + ObjectProvider grailsMimeTypesWebMvcConfigurer) { + return new GrailsContentNegotiationManagerPostProcessor(() -> grailsApplication.getObject().config, () -> grailsMimeTypesWebMvcConfigurer.getObject().contentNegotiationStrategy) } diff --git a/grails-mimetypes/src/main/groovy/org/grails/web/mime/GrailsContentNegotiationManagerPostProcessor.groovy b/grails-mimetypes/src/main/groovy/org/grails/web/mime/GrailsContentNegotiationManagerPostProcessor.groovy index 463c60e50f3..b5a3f11ea05 100644 --- a/grails-mimetypes/src/main/groovy/org/grails/web/mime/GrailsContentNegotiationManagerPostProcessor.groovy +++ b/grails-mimetypes/src/main/groovy/org/grails/web/mime/GrailsContentNegotiationManagerPostProcessor.groovy @@ -24,9 +24,9 @@ import groovy.transform.CompileStatic import org.springframework.beans.BeansException import org.springframework.beans.factory.config.BeanPostProcessor -import org.springframework.core.env.Environment import org.springframework.web.accept.ContentNegotiationManager +import grails.config.Config import grails.config.Settings /** @@ -34,25 +34,27 @@ import grails.config.Settings * the {@code grails.mime} rules Grails keeps to the requests a URL mapping handles (see * {@link GrailsContentNegotiationManager}), so that what Spring MVC writes for them, such as a {@code ResponseEntity} or * a {@code ProblemDetail} an action returns or {@code respond} writes, is negotiated as Grails resolves their formats. - * Without it, Spring MVC's manager is left as it is. + * Without it, Spring MVC's manager is left as it is. The setting is read from the application's configuration, which + * the strategy that resolves Grails formats reads it from too, so that the two never disagree. * * @since 9.0 */ @CompileStatic class GrailsContentNegotiationManagerPostProcessor implements BeanPostProcessor { - private final Environment environment + private final Supplier config private final Supplier grailsStrategy /** - * @param environment the environment the setting is read from + * @param config supplies the application's configuration, which the setting is read from as Spring MVC's manager is + * created, since a post-processor is created before the other beans * @param grailsStrategy supplies the strategy that resolves Grails formats, which Spring MVC's manager is created * before */ - GrailsContentNegotiationManagerPostProcessor(Environment environment, + GrailsContentNegotiationManagerPostProcessor(Supplier config, Supplier grailsStrategy) { - this.environment = environment + this.config = config this.grailsStrategy = grailsStrategy } @@ -60,7 +62,7 @@ class GrailsContentNegotiationManagerPostProcessor implements BeanPostProcessor Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { if (beanName == GrailsContentNegotiationStrategy.MVC_CONTENT_NEGOTIATION_MANAGER && bean instanceof ContentNegotiationManager && !(bean instanceof GrailsContentNegotiationManager) && - environment.getProperty(Settings.MIME_NEGOTIATION_SPRING, Boolean, + config.get().getProperty(Settings.MIME_NEGOTIATION_SPRING, Boolean, Boolean.valueOf(Settings.MIME_NEGOTIATION_SPRING_DEFAULT))) { return new GrailsContentNegotiationManager((ContentNegotiationManager) bean, grailsStrategy) } diff --git a/grails-mimetypes/src/test/groovy/org/grails/web/mime/SpringFormatNegotiationSpec.groovy b/grails-mimetypes/src/test/groovy/org/grails/web/mime/SpringFormatNegotiationSpec.groovy index 11915007f54..7ab8f493b76 100644 --- a/grails-mimetypes/src/test/groovy/org/grails/web/mime/SpringFormatNegotiationSpec.groovy +++ b/grails-mimetypes/src/test/groovy/org/grails/web/mime/SpringFormatNegotiationSpec.groovy @@ -24,6 +24,7 @@ import org.springframework.context.annotation.Configuration import org.springframework.context.annotation.Import import org.springframework.core.env.ConfigurableEnvironment import org.springframework.core.env.MapPropertySource +import org.springframework.core.env.MutablePropertySources import org.springframework.http.MediaType import org.springframework.mock.web.MockHttpServletRequest import org.springframework.mock.web.MockHttpServletResponse @@ -377,6 +378,28 @@ class SpringFormatNegotiationSpec extends Specification { request.mimeTypes*.name == ['image/png'] } + void "the setting is read from the application's configuration, for Spring MVC's manager as for Grails formats, where the environment says #environment"() { + given: 'a configuration of the application that is not the environment, as one a test builds by hand' + context = new AnnotationConfigWebApplicationContext() + context.servletContext = new MockServletContext() + context.environment.propertySources.addFirst(new MapPropertySource('test', [ + (Settings.MIME_NEGOTIATION_SPRING) : environment, + (SeparateConfigConfiguration.CONFIGURED): configured + ])) + context.register(SeparateConfigConfiguration) + context.refresh() + request('Accept': '*/*, application/json') + + expect: + (manager() instanceof GrailsContentNegotiationManager) == configured + GrailsWebRequest.lookup().currentResponse.format == format + + where: + environment | configured || format + false | true || 'json' + true | false || 'all' + } + void 'without the setting, the Grails 9 rules resolve the formats'() { given: start([:]) @@ -437,6 +460,27 @@ class SpringFormatNegotiationSpec extends Specification { } } + /** An application whose configuration has the setting the test gives it apart from the environment. */ + @Configuration(proxyBeanMethods = false) + @EnableWebMvc + @Import(MimeTypesConfiguration) + static class SeparateConfigConfiguration { + + static final String CONFIGURED = 'test.configured.negotiation' + + @Bean + GrailsApplication grailsApplication(ApplicationContext applicationContext, ConfigurableEnvironment environment) { + def propertySources = new MutablePropertySources() + propertySources.addFirst(new MapPropertySource('configured', + [(Settings.MIME_NEGOTIATION_SPRING): environment.getProperty(CONFIGURED, Boolean)])) + def application = new DefaultGrailsApplication() + application.config = new PropertySourcesConfig(propertySources) + application.applicationContext = applicationContext + application.mainContext = applicationContext + application + } + } + /** Enables Spring MVC's parameter negotiation, as {@code spring.mvc.contentnegotiation.*} does, where the test says. */ @Configuration(proxyBeanMethods = false) static class ParameterConfiguration implements WebMvcConfigurer { From 840fc4a56666beef8f834c144fd7f3d33adc564b Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Sat, 14 Nov 2026 12:44:09 -0800 Subject: [PATCH 10/21] Test Spring MVC format negotiation in an application of its own The functional spec with grails.mime.negotiation.spring ran in app1 with @TestPropertySource, which starts a second application context in the test JVM. GORM's static API then answered for that context, so the GORM specs of app1 that ran after it failed with "No Session found for current thread". The spec moves to grails-test-examples/spring-format-negotiation, whose application.yml sets the setting, with the Spring MVC endpoint and the actions it calls; app1 keeps the spec of the Grails rules, which runs in its own context. --- .../contentneg/SpringWrittenController.groovy | 6 +-- .../init/functionaltests/Application.groovy | 11 ---- .../GrailsFormatNegotiationSpec.groovy | 50 +++++++++++++++++++ .../spring-format-negotiation/build.gradle | 42 ++++++++++++++++ .../grails-app/conf/application.yml | 32 ++++++++++++ .../grails-app/conf/logback.xml | 38 ++++++++++++++ .../SpringWrittenController.groovy | 44 ++++++++++++++++ .../UrlMappings.groovy | 30 +++++++++++ .../Application.groovy | 46 +++++++++++++++++ .../SpringFormatNegotiationSpec.groovy | 31 +----------- .../SpringNegotiationApi.groovy | 2 +- settings.gradle | 2 + 12 files changed, 288 insertions(+), 46 deletions(-) create mode 100644 grails-test-examples/app1/src/integration-test/groovy/functionaltests/contentneg/GrailsFormatNegotiationSpec.groovy create mode 100644 grails-test-examples/spring-format-negotiation/build.gradle create mode 100644 grails-test-examples/spring-format-negotiation/grails-app/conf/application.yml create mode 100644 grails-test-examples/spring-format-negotiation/grails-app/conf/logback.xml create mode 100644 grails-test-examples/spring-format-negotiation/grails-app/controllers/springformatnegotiation/SpringWrittenController.groovy create mode 100644 grails-test-examples/spring-format-negotiation/grails-app/controllers/springformatnegotiation/UrlMappings.groovy create mode 100644 grails-test-examples/spring-format-negotiation/grails-app/init/springformatnegotiation/Application.groovy rename grails-test-examples/{app1/src/integration-test/groovy/functionaltests/contentneg => spring-format-negotiation/src/integration-test/groovy/springformatnegotiation}/SpringFormatNegotiationSpec.groovy (72%) rename grails-test-examples/{app1/src/main/groovy/functionaltests/contentneg => spring-format-negotiation/src/main/groovy/springformatnegotiation}/SpringNegotiationApi.groovy (97%) diff --git a/grails-test-examples/app1/grails-app/controllers/functionaltests/contentneg/SpringWrittenController.groovy b/grails-test-examples/app1/grails-app/controllers/functionaltests/contentneg/SpringWrittenController.groovy index 06398002916..9dd265d1850 100644 --- a/grails-test-examples/app1/grails-app/controllers/functionaltests/contentneg/SpringWrittenController.groovy +++ b/grails-test-examples/app1/grails-app/controllers/functionaltests/contentneg/SpringWrittenController.groovy @@ -22,7 +22,7 @@ import org.springframework.http.ResponseEntity /** * Actions whose values Spring MVC writes, and one that answers with the formats Grails resolves for the request, which - * {@code grails.mime.negotiation.spring} negotiates alike. + * the Grails rules negotiate without {@code grails.mime.negotiation.spring}. */ class SpringWrittenController { @@ -37,8 +37,4 @@ class SpringWrittenController { def formats() { render(contentType: 'text/plain', text: "${response.format}|${request.format}") } - - def forwardToSpring() { - forward(uri: '/springNegotiation') - } } diff --git a/grails-test-examples/app1/grails-app/init/functionaltests/Application.groovy b/grails-test-examples/app1/grails-app/init/functionaltests/Application.groovy index 4019ce93a86..dcc99a5d58b 100644 --- a/grails-test-examples/app1/grails-app/init/functionaltests/Application.groovy +++ b/grails-test-examples/app1/grails-app/init/functionaltests/Application.groovy @@ -19,11 +19,8 @@ package functionaltests -import org.springframework.context.annotation.Bean - import grails.boot.GrailsApp import grails.boot.config.GrailsAutoConfiguration -import functionaltests.contentneg.SpringNegotiationApi class Application extends GrailsAutoConfiguration { static { @@ -33,12 +30,4 @@ class Application extends GrailsAutoConfiguration { static void main(String[] args) { GrailsApp.run(Application) } - - /** - * A Spring MVC endpoint beside the Grails controllers, which content negotiation leaves to Spring MVC. - */ - @Bean - SpringNegotiationApi springNegotiationApi() { - new SpringNegotiationApi() - } } diff --git a/grails-test-examples/app1/src/integration-test/groovy/functionaltests/contentneg/GrailsFormatNegotiationSpec.groovy b/grails-test-examples/app1/src/integration-test/groovy/functionaltests/contentneg/GrailsFormatNegotiationSpec.groovy new file mode 100644 index 00000000000..26073054254 --- /dev/null +++ b/grails-test-examples/app1/src/integration-test/groovy/functionaltests/contentneg/GrailsFormatNegotiationSpec.groovy @@ -0,0 +1,50 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package functionaltests.contentneg + +import spock.lang.Specification +import spock.lang.Tag + +import grails.testing.mixin.integration.Integration +import org.apache.grails.testing.http.client.HttpClientSupport + +/** + * Without {@code grails.mime.negotiation.spring}, Grails resolves formats with its own rules, and Spring MVC writes the + * values of actions as the {@code Accept} header asks. + */ +@Integration +@Tag('http-client') +class GrailsFormatNegotiationSpec extends Specification implements HttpClientSupport { + + void 'a value Spring MVC writes for an action is in the type the Accept header asks for, whatever its URL extension'() { + expect: + http('/springWritten/entity.html', Accept: '*/*').assertStatus(200).contentType.startsWith('application/json') + http('/springWritten/text.json', Accept: 'text/plain').assertStatus(200).contentType.startsWith('text/plain') + } + + void 'the formats Grails resolves follow the Grails rules: #accept'() { + expect: + http('/springWritten/formats', Accept: accept).assertStatus(200).assertEquals(formats) + + where: + accept || formats + '*/*, application/json' || 'all|all' + 'image/png' || 'all|all' + } +} diff --git a/grails-test-examples/spring-format-negotiation/build.gradle b/grails-test-examples/spring-format-negotiation/build.gradle new file mode 100644 index 00000000000..8facc4f7193 --- /dev/null +++ b/grails-test-examples/spring-format-negotiation/build.gradle @@ -0,0 +1,42 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +plugins { + id 'org.apache.grails.buildsrc.properties' + id 'org.apache.grails.buildsrc.dependency-validator' + id 'org.apache.grails.buildsrc.compile' + id 'org.apache.grails.gradle.grails-web' +} + +version = '0.1' +group = 'springformatnegotiation' + +dependencies { + + implementation platform(project(':grails-bom')) + implementation 'org.apache.grails:grails-dependencies-starter-web' + + integrationTestImplementation 'org.apache.grails:grails-testing-support-http-client' + integrationTestImplementation 'org.apache.grails:grails-testing-support-web' +} + +apply { + from rootProject.layout.projectDirectory.file('gradle/functional-test-config.gradle') + from rootProject.layout.projectDirectory.file('gradle/grails-extension-gradle-config.gradle') +} diff --git a/grails-test-examples/spring-format-negotiation/grails-app/conf/application.yml b/grails-test-examples/spring-format-negotiation/grails-app/conf/application.yml new file mode 100644 index 00000000000..4b8bc514017 --- /dev/null +++ b/grails-test-examples/spring-format-negotiation/grails-app/conf/application.yml @@ -0,0 +1,32 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You under the Apache License, Version 2.0 +# (the "License"); you may not use this file except in compliance with +# the License. You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +--- +grails: + profile: web + codegen: + defaultPackage: springformatnegotiation + mime: + negotiation: + spring: true +info: + app: + name: '@info.app.name@' + version: '@info.app.version@' + grailsVersion: '@info.app.grailsVersion@' +spring: + groovy: + template: + check-template-location: false diff --git a/grails-test-examples/spring-format-negotiation/grails-app/conf/logback.xml b/grails-test-examples/spring-format-negotiation/grails-app/conf/logback.xml new file mode 100644 index 00000000000..2671b7ce98d --- /dev/null +++ b/grails-test-examples/spring-format-negotiation/grails-app/conf/logback.xml @@ -0,0 +1,38 @@ + + + + + + + + + + UTF-8 + %clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(%5p) %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n%wex + + + + + + + + diff --git a/grails-test-examples/spring-format-negotiation/grails-app/controllers/springformatnegotiation/SpringWrittenController.groovy b/grails-test-examples/spring-format-negotiation/grails-app/controllers/springformatnegotiation/SpringWrittenController.groovy new file mode 100644 index 00000000000..57a570aaaac --- /dev/null +++ b/grails-test-examples/spring-format-negotiation/grails-app/controllers/springformatnegotiation/SpringWrittenController.groovy @@ -0,0 +1,44 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package springformatnegotiation + +import org.springframework.http.ResponseEntity + +/** + * Actions whose values Spring MVC writes, and one that answers with the formats Grails resolves for the request, which + * {@code grails.mime.negotiation.spring} negotiates alike. + */ +class SpringWrittenController { + + def entity() { + ResponseEntity.ok([title: 'Grails']) + } + + def text() { + ResponseEntity.ok('Grails') + } + + def formats() { + render(contentType: 'text/plain', text: "${response.format}|${request.format}") + } + + def forwardToSpring() { + forward(uri: '/springNegotiation') + } +} diff --git a/grails-test-examples/spring-format-negotiation/grails-app/controllers/springformatnegotiation/UrlMappings.groovy b/grails-test-examples/spring-format-negotiation/grails-app/controllers/springformatnegotiation/UrlMappings.groovy new file mode 100644 index 00000000000..504d9cc381e --- /dev/null +++ b/grails-test-examples/spring-format-negotiation/grails-app/controllers/springformatnegotiation/UrlMappings.groovy @@ -0,0 +1,30 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package springformatnegotiation + +class UrlMappings { + + static mappings = { + "/$controller/$action?/$id?(.$format)?" { + constraints { + // apply constraints here + } + } + } +} diff --git a/grails-test-examples/spring-format-negotiation/grails-app/init/springformatnegotiation/Application.groovy b/grails-test-examples/spring-format-negotiation/grails-app/init/springformatnegotiation/Application.groovy new file mode 100644 index 00000000000..4d5a4e04800 --- /dev/null +++ b/grails-test-examples/spring-format-negotiation/grails-app/init/springformatnegotiation/Application.groovy @@ -0,0 +1,46 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package springformatnegotiation + +import groovy.transform.CompileStatic + +import org.springframework.context.annotation.Bean + +import grails.boot.GrailsApp +import grails.boot.config.GrailsAutoConfiguration + +/** + * An application that resolves Grails formats with Spring MVC's content negotiation, as + * {@code grails.mime.negotiation.spring} in its {@code application.yml} says. + */ +@CompileStatic +class Application extends GrailsAutoConfiguration { + + static void main(String[] args) { + GrailsApp.run(Application, args) + } + + /** + * A Spring MVC endpoint beside the Grails controllers, which content negotiation leaves to Spring MVC. + */ + @Bean + SpringNegotiationApi springNegotiationApi() { + new SpringNegotiationApi() + } +} diff --git a/grails-test-examples/app1/src/integration-test/groovy/functionaltests/contentneg/SpringFormatNegotiationSpec.groovy b/grails-test-examples/spring-format-negotiation/src/integration-test/groovy/springformatnegotiation/SpringFormatNegotiationSpec.groovy similarity index 72% rename from grails-test-examples/app1/src/integration-test/groovy/functionaltests/contentneg/SpringFormatNegotiationSpec.groovy rename to grails-test-examples/spring-format-negotiation/src/integration-test/groovy/springformatnegotiation/SpringFormatNegotiationSpec.groovy index 7bdea2c334e..b261db0a940 100644 --- a/grails-test-examples/app1/src/integration-test/groovy/functionaltests/contentneg/SpringFormatNegotiationSpec.groovy +++ b/grails-test-examples/spring-format-negotiation/src/integration-test/groovy/springformatnegotiation/SpringFormatNegotiationSpec.groovy @@ -16,9 +16,8 @@ * specific language governing permissions and limitations * under the License. */ -package functionaltests.contentneg +package springformatnegotiation -import org.springframework.test.context.TestPropertySource import spock.lang.Specification import spock.lang.Tag @@ -26,13 +25,12 @@ import grails.testing.mixin.integration.Integration import org.apache.grails.testing.http.client.HttpClientSupport /** - * With {@code grails.mime.negotiation.spring}, Grails formats are resolved with Spring MVC's content negotiation, and + * With {@code grails.mime.negotiation.spring}, which this application's configuration sets, Grails formats are resolved with Spring MVC's content negotiation, and * what Spring MVC writes for an action is negotiated with the format the request names, while a Spring MVC endpoint is * negotiated as before. */ @Integration @Tag('http-client') -@TestPropertySource(properties = 'grails.mime.negotiation.spring=true') class SpringFormatNegotiationSpec extends Specification implements HttpClientSupport { void 'a value Spring MVC writes for an action is in the format of its URL extension, which a map cannot be written in as HTML'() { @@ -83,28 +81,3 @@ class SpringFormatNegotiationSpec extends Specification implements HttpClientSup http('/springWritten/forwardToSpring?format=xml', Accept: 'application/json').assertStatus(200).assertJson([title: 'Grails']) } } - -/** - * Without {@code grails.mime.negotiation.spring}, Grails resolves formats with its own rules, and Spring MVC writes the - * values of actions as the {@code Accept} header asks. - */ -@Integration -@Tag('http-client') -class GrailsFormatNegotiationSpec extends Specification implements HttpClientSupport { - - void 'a value Spring MVC writes for an action is in the type the Accept header asks for, whatever its URL extension'() { - expect: - http('/springWritten/entity.html', Accept: '*/*').assertStatus(200).contentType.startsWith('application/json') - http('/springWritten/text.json', Accept: 'text/plain').assertStatus(200).contentType.startsWith('text/plain') - } - - void 'the formats Grails resolves follow the Grails rules: #accept'() { - expect: - http('/springWritten/formats', Accept: accept).assertStatus(200).assertEquals(formats) - - where: - accept || formats - '*/*, application/json' || 'all|all' - 'image/png' || 'all|all' - } -} diff --git a/grails-test-examples/app1/src/main/groovy/functionaltests/contentneg/SpringNegotiationApi.groovy b/grails-test-examples/spring-format-negotiation/src/main/groovy/springformatnegotiation/SpringNegotiationApi.groovy similarity index 97% rename from grails-test-examples/app1/src/main/groovy/functionaltests/contentneg/SpringNegotiationApi.groovy rename to grails-test-examples/spring-format-negotiation/src/main/groovy/springformatnegotiation/SpringNegotiationApi.groovy index cdfbc687039..8eda1e3bffa 100644 --- a/grails-test-examples/app1/src/main/groovy/functionaltests/contentneg/SpringNegotiationApi.groovy +++ b/grails-test-examples/spring-format-negotiation/src/main/groovy/springformatnegotiation/SpringNegotiationApi.groovy @@ -16,7 +16,7 @@ * specific language governing permissions and limitations * under the License. */ -package functionaltests.contentneg +package springformatnegotiation import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.RestController diff --git a/settings.gradle b/settings.gradle index b14163544e0..74a4a2eee1a 100644 --- a/settings.gradle +++ b/settings.gradle @@ -576,6 +576,7 @@ include( 'grails-test-examples-datasources', 'grails-test-examples-demo33', 'grails-test-examples-enable-mvc-check', + 'grails-test-examples-spring-format-negotiation', 'grails-test-examples-exploded', 'grails-test-examples-external-configuration', 'grails-test-examples-geb', @@ -646,6 +647,7 @@ project(':grails-test-examples-issue-views-182').projectDir = file('grails-test- project(':grails-test-examples-issue-11102').projectDir = file('grails-test-examples/issue-11102') project(':grails-test-examples-demo33').projectDir = file('grails-test-examples/demo33') project(':grails-test-examples-enable-mvc-check').projectDir = file('grails-test-examples/enable-mvc-check') +project(':grails-test-examples-spring-format-negotiation').projectDir = file('grails-test-examples/spring-format-negotiation') project(':grails-test-examples-plugins-loadfirst').projectDir = file('grails-test-examples/plugins/loadfirst') project(':grails-test-examples-plugins-loadsecond').projectDir = file('grails-test-examples/plugins/loadsecond') project(':grails-test-examples-plugins-loadafter').projectDir = file('grails-test-examples/plugins/loadafter') From 1f5f19f9dfd6d3436b28cdc83a4b956c7130e43b Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Sat, 14 Nov 2026 15:14:40 -0800 Subject: [PATCH 11/21] Read the all format as any type where it is not configured With grails.mime.negotiation.spring and a grails.mime.types that does not list all, a client that accepts any type resolves to the all format, which reading response.format saves as the response format. respond then resolved that saved format to no type, and answered 406: the all format is now */*, any type, as Spring MVC reads it, whether or not grails.mime.types lists it. ?format=all then leaves the format to the Accept header there too, for Grails formats and for what Spring MVC writes. --- .../GrailsContentNegotiationStrategy.groovy | 16 ++++++--- .../mime/SpringFormatNegotiationSpec.groovy | 34 ++++++++++++++++++ .../SpringFormatNegotiationRespondSpec.groovy | 36 +++++++++++++++++++ 3 files changed, 81 insertions(+), 5 deletions(-) diff --git a/grails-mimetypes/src/main/groovy/org/grails/web/mime/GrailsContentNegotiationStrategy.groovy b/grails-mimetypes/src/main/groovy/org/grails/web/mime/GrailsContentNegotiationStrategy.groovy index 54c7226b527..05555dd382d 100644 --- a/grails-mimetypes/src/main/groovy/org/grails/web/mime/GrailsContentNegotiationStrategy.groovy +++ b/grails-mimetypes/src/main/groovy/org/grails/web/mime/GrailsContentNegotiationStrategy.groovy @@ -158,15 +158,19 @@ class GrailsContentNegotiationStrategy { * * @param format the format * @return its first configured type; for a format that is not configured, the first configured type, as Grails 9 - * answers, or, with {@code grails.mime.negotiation.spring}, {@code null}, since the request accepts no - * configured type + * answers, or, with {@code grails.mime.negotiation.spring}, {@code null}, since the request accepts no configured + * type, except for the {@code all} format, which is {@code */*}, any type * @since 9.0 */ MimeType resolveFormat(Object format) { MimeType mimeType = mimeTypes.find { MimeType configured -> configured.extension == format } - if (mimeType != null || springNegotiation) { + if (mimeType != null) { return mimeType } + if (springNegotiation) { + // the all format is any type, as Spring MVC reads */*, also where grails.mime.types does not list it + return format == ALL_FORMAT ? new MimeType(MimeType.ALL.name, ALL_FORMAT) : null + } return mimeTypes.find { it } } @@ -229,7 +233,8 @@ class GrailsContentNegotiationStrategy { * suffix, as Spring MVC's JSON and XML converters write them. * * @param format the format - * @return the media types, or {@code null} where no type of the format is configured + * @return the media types, {@code */*} for the {@code all} format where no type of it is configured, or + * {@code null} where no type of another format is * @since 9.0 */ List mediaTypesOf(String format) { @@ -240,7 +245,8 @@ class GrailsContentNegotiationStrategy { } } if (types.isEmpty()) { - return null + // the all format is any type, also where grails.mime.types does not list it + return format == ALL_FORMAT ? [MediaType.ALL] : null } if (format != null && SUFFIX_FORMATS.contains(format)) { MediaType suffixed = new MediaType('application', "*+${format}".toString()) diff --git a/grails-mimetypes/src/test/groovy/org/grails/web/mime/SpringFormatNegotiationSpec.groovy b/grails-mimetypes/src/test/groovy/org/grails/web/mime/SpringFormatNegotiationSpec.groovy index 7ab8f493b76..1c67f3f7e9e 100644 --- a/grails-mimetypes/src/test/groovy/org/grails/web/mime/SpringFormatNegotiationSpec.groovy +++ b/grails-mimetypes/src/test/groovy/org/grails/web/mime/SpringFormatNegotiationSpec.groovy @@ -257,6 +257,40 @@ class SpringFormatNegotiationSpec extends Specification { } == 'html' } + void 'a client that accepts any type answers respond with any format after its format is read, #how, also where the all format is not configured'() { + given: + start((Settings.MIME_NEGOTIATION_SPRING): true, 'grails.mime.types': [json: 'application/json', html: 'text/html']) + def request = request(accept ? ['Accept': accept] : [:]) + def response = GrailsWebRequest.lookup().currentResponse + + when: 'the format is read, which saves it for the response, and then the types respond answers in' + String format = response.format + def formatAware = response.mimeTypesFormatAware.toList() + + then: + format == 'all' + formatAware*.extension == ['all'] + formatAware*.name == ['*/*'] + response.mimeType.name == '*/*' + + where: + how | accept + 'with Accept: */*' | '*/*' + 'without Accept' | null + } + + void 'a format parameter of all, where the all format is not configured, leaves the format to the Accept header'() { + given: + start((Settings.MIME_NEGOTIATION_SPRING): true, 'grails.mime.types': [json: 'application/json', html: 'text/html']) + def request = request('Accept': 'application/json') + handledBy(request, urlMapping()) + GrailsWebRequest.lookup().params.format = 'all' + + expect: + GrailsWebRequest.lookup().currentResponse.format == 'json' + manager().resolveMediaTypes(new ServletWebRequest(request)) == [MediaType.APPLICATION_JSON] + } + void 'a wildcard is of the all format, which withFormat answers with the first block compatible with it: #result for #accept'() { given: start((Settings.MIME_NEGOTIATION_SPRING): true) diff --git a/grails-test-suite-web/src/test/groovy/grails/rest/web/SpringFormatNegotiationRespondSpec.groovy b/grails-test-suite-web/src/test/groovy/grails/rest/web/SpringFormatNegotiationRespondSpec.groovy index 5a4195e05af..a6a5118f31b 100644 --- a/grails-test-suite-web/src/test/groovy/grails/rest/web/SpringFormatNegotiationRespondSpec.groovy +++ b/grails-test-suite-web/src/test/groovy/grails/rest/web/SpringFormatNegotiationRespondSpec.groovy @@ -148,6 +148,42 @@ class SpringFormatNegotiationRespondSpec extends Specification implements Contro } } +/** + * With {@code grails.mime.negotiation.spring} and a {@code grails.mime.types} that does not list the {@code all} format, + * a client that accepts any type is still answered in the action's first format, whatever read the response format first. + */ +class SpringFormatNegotiationWithoutAllRespondSpec extends Specification implements ControllerUnitTest { + + Closure doWithConfig() { + { config -> + config[Settings.WEB_RENDERING_JSON_SPRING] = true + config[Settings.MIME_NEGOTIATION_SPRING] = true + config[Settings.MIME_TYPES] = [json: 'application/json', xml: 'application/xml', html: 'text/html'] + } + } + + void 'a client that accepts any type is answered in the first format of the action after the response format is read, #how'() { + given: + if (accept) { + request.addHeader('Accept', accept) + } + + when: + String format = response.format + controller.respond([title: 'Grails'], formats: ['json', 'xml']) + + then: + format == 'all' + response.status == 200 + response.contentType.startsWith('application/json') + + where: + how | accept + 'with Accept */*' | '*/*' + 'without Accept' | null + } +} + /** * Without {@code grails.mime.negotiation.spring}, the Grails 9 rules resolve the format {@code respond} answers in. */ From f314e849f714e01ab5fa7ca7957ddbadcef19641 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Sat, 14 Nov 2026 15:14:50 -0800 Subject: [PATCH 12/21] Keep a +xml type ahead of the XML type of equal quality grails.mime.negotiation.spring took the types of the Accept header in Spring MVC's order alone, so Accept: application/xml, application/atom+xml resolved to xml where the Grails rules resolve it to atom. A type with the +xml suffix of the quality of the first application/xml or text/xml now comes ahead of it, each one later in the header in front of those before it, as the Grails rules order them, for Grails formats and, for a request a URL mapping handles, for what Spring MVC writes. The comparison record loses the atom answers, and the guide and upgrade notes list the rule as kept; they also describe the all format of the previous commit. --- .../guide/theWebLayer/contentNegotiation.adoc | 10 ++++--- .../src/en/guide/upgrading/upgrading90x.adoc | 9 +++--- ...eptHeaderContentNegotiationStrategy.groovy | 13 +++++---- .../GrailsContentNegotiationStrategy.groovy | 29 ++++++++++++++++++- .../FormatNegotiationComparisonSpec.groovy | 8 ++--- .../mime/SpringFormatNegotiationSpec.groovy | 22 +++++++++++++- 6 files changed, 72 insertions(+), 19 deletions(-) diff --git a/grails-doc/src/en/guide/theWebLayer/contentNegotiation.adoc b/grails-doc/src/en/guide/theWebLayer/contentNegotiation.adoc index 6aee23a57d9..e939ecc2f0a 100644 --- a/grails-doc/src/en/guide/theWebLayer/contentNegotiation.adoc +++ b/grails-doc/src/en/guide/theWebLayer/contentNegotiation.adoc @@ -287,9 +287,10 @@ setting: * The `Accept` header is read by Spring MVC's manager, with its strategies, so the `spring.mvc.contentnegotiation.*` properties apply to the Grails formats as they do to Spring MVC, and its media types are taken in the order Spring MVC -takes them: by quality, then a more specific type ahead of a less specific one, then in the order the header lists them. +takes them: by quality, then a more specific type ahead of a less specific one, then in the order the header lists them, +except that a type with the `+xml` suffix comes ahead of the XML type of equal quality, as the Grails rules take it. `Accept: */*, application/json` is the `json` format, where the Grails rules give `all`, and -`Accept: application/xml, application/atom+xml` is `xml`, where they give `atom`. +`Accept: application/xml, application/atom+xml` is `atom`, as they give. * Each media type is the format `grails.mime.types`, or a `MimeTypeProvider` bean such as a renderer, gives it. A type with the `+json` or `+xml` suffix that no configured type names, such as `application/merge-patch+json` or `application/problem+xml`, is the `json` or the `xml` format, as Spring MVC's JSON and XML converters write such types. @@ -303,7 +304,8 @@ Spring cannot read, has no format: `response.format` and `response.mimeType` are that accepts any type, with the `all` format. * The `format` parameter and a URL extension name the format, ahead of the `Accept` header, as before. The first value of the parameter counts, as for Spring MVC; a format no type is configured for is not acceptable, where the Grails rules -answer in the first configured format; and the `all` format leaves the format to the `Accept` header. +answer in the first configured format; and the `all` format, which is any type whether or not `grails.mime.types` lists +it, leaves the format to the `Accept` header. * `grails.mime.use.accept.header` and `grails.mime.disable.accept.header.*` ignore the `Accept` header as before. * The `format` parameter, the URL extension and the `Accept` header settings also decide what Spring MVC writes for a request a URL mapping handles, so that it is in the format Grails resolves for the request: an action that returns a @@ -333,7 +335,7 @@ acceptable, and the `all` format leaves the choice to the `Accept` header. |Dropped: both are the `xml` format, which comes in Spring MVC's order. |A type with the `+xml` suffix comes ahead of `application/xml` of equal quality -|Dropped: the types come in Spring MVC's order. +|Kept, also for what Spring MVC writes for the request. |The problem types of RFC 9457 are the `json` and `xml` formats |Extended to any type with the `+json` or `+xml` suffix that no configured type names. diff --git a/grails-doc/src/en/guide/upgrading/upgrading90x.adoc b/grails-doc/src/en/guide/upgrading/upgrading90x.adoc index dad7baaca1e..678470e4f69 100644 --- a/grails-doc/src/en/guide/upgrading/upgrading90x.adoc +++ b/grails-doc/src/en/guide/upgrading/upgrading90x.adoc @@ -1296,8 +1296,9 @@ The setting changes these answers, which the framework's tests record by running * *The order of the `Accept` header.* Spring MVC takes a more specific type ahead of a less specific one of equal quality, where the Grails rules keep the order of the header: `Accept: */*, application/json` is the `json` format, -where it is `all` without the setting, and `withFormat` runs the `json` block rather than its first. A type with the `+xml` suffix no longer comes ahead -of `application/xml`: `Accept: application/xml, application/atom+xml` is `xml`, where it is `atom` without the setting. +where it is `all` without the setting, and `withFormat` runs the `json` block rather than its first. A type with the +`+xml` suffix still comes ahead of the XML type of equal quality: `Accept: application/xml, application/atom+xml` is +`atom` either way, and Spring MVC now writes what an action returns in that order too. * *Types with the `+json` and `+xml` suffixes.* A type no configured type names, such as `application/merge-patch+json`, `application/soap+xml` or, without a `hal` format, `application/hal+json`, is the `json` or `xml` format, where the Grails rules read only the problem types of RFC 9457 so and answer any other as `all`. In `Content-Type` too: a body sent @@ -1321,8 +1322,8 @@ too. * *Without the `all` format.* Where `grails.mime.types` does not list `all`, a request without an `Accept` header is of the `all` format, as one that sends `Accept: */*` is, where the Grails rules give the first configured format, so `withFormat` runs its `*` block, or its first block, rather than the block of that format. A type of quality `0` comes -after any other, so `Accept: application/json;q=0, */*;q=0.1` is `all`, where it is otherwise `json`. `?format=all` is -then an unknown format. +after any other, so `Accept: application/json;q=0, */*;q=0.1` is `all`, where it is otherwise `json`. `?format=all` +leaves the format to the `Accept` header there too, where the Grails rules give the first configured format. * *Wildcards.* A wildcard such as `text/*` is the `all` format as before, but `withFormat` runs the first block of a format with a type compatible with it, and `respond` answers in the first such format of the action, where the Grails rules run the first block and answer in the first format: `withFormat { pdf {...}; html {...} }` runs the `html` block for diff --git a/grails-mimetypes/src/main/groovy/org/grails/web/mime/GrailsAcceptHeaderContentNegotiationStrategy.groovy b/grails-mimetypes/src/main/groovy/org/grails/web/mime/GrailsAcceptHeaderContentNegotiationStrategy.groovy index acbd45f240b..41ece6b7506 100644 --- a/grails-mimetypes/src/main/groovy/org/grails/web/mime/GrailsAcceptHeaderContentNegotiationStrategy.groovy +++ b/grails-mimetypes/src/main/groovy/org/grails/web/mime/GrailsAcceptHeaderContentNegotiationStrategy.groovy @@ -32,8 +32,9 @@ import org.springframework.web.context.request.NativeWebRequest /** * The strategy of Spring MVC's content negotiation manager that reads the {@code Accept} header in place of Spring MVC's * own, and ignores it for a request a URL mapping handles where {@code grails.mime.use.accept.header} or - * {@code grails.mime.disable.accept.header.*} say so, so that what Spring MVC writes for it is in the format Grails - * resolves for it. Any other request, such as one a Spring MVC endpoint handles, is negotiated by the strategy it + * {@code grails.mime.disable.accept.header.*} say so, and otherwise takes a type with the {@code +xml} suffix ahead of the + * XML type of equal quality, as Grails does, so that what Spring MVC writes for it is in the format Grails resolves for + * it. Any other request, such as one a Spring MVC endpoint handles, is negotiated by the strategy it * replaces. It is a {@link HeaderContentNegotiationStrategy}, so that it is found as Spring MVC's is. * * @since 9.0 @@ -64,10 +65,12 @@ class GrailsAcceptHeaderContentNegotiationStrategy extends HeaderContentNegotiat @Override List resolveMediaTypes(NativeWebRequest webRequest) throws HttpMediaTypeNotAcceptableException { HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest) - if (request != null && GrailsContentNegotiationStrategy.handlesRequest(request) && - grailsStrategy.get().ignoresAcceptHeader(request)) { + boolean handled = request != null && GrailsContentNegotiationStrategy.handlesRequest(request) + if (handled && grailsStrategy.get().ignoresAcceptHeader(request)) { return MEDIA_TYPE_ALL_LIST } - return springStrategy.resolveMediaTypes(webRequest) + List mediaTypes = springStrategy.resolveMediaTypes(webRequest) + // in the order Grails reads them, so that what Spring MVC writes is in the format Grails resolves + return handled ? GrailsContentNegotiationStrategy.preferringSuffixedXml(mediaTypes) : mediaTypes } } diff --git a/grails-mimetypes/src/main/groovy/org/grails/web/mime/GrailsContentNegotiationStrategy.groovy b/grails-mimetypes/src/main/groovy/org/grails/web/mime/GrailsContentNegotiationStrategy.groovy index 05555dd382d..00b6166eecf 100644 --- a/grails-mimetypes/src/main/groovy/org/grails/web/mime/GrailsContentNegotiationStrategy.groovy +++ b/grails-mimetypes/src/main/groovy/org/grails/web/mime/GrailsContentNegotiationStrategy.groovy @@ -347,7 +347,7 @@ class GrailsContentNegotiationStrategy { } List resolved = strategy.resolveMediaTypes(webRequest) if (resolved != ContentNegotiationStrategy.MEDIA_TYPE_ALL_LIST) { - return resolved + return preferringSuffixedXml(resolved) } } } @@ -358,6 +358,33 @@ class GrailsContentNegotiationStrategy { return ContentNegotiationStrategy.MEDIA_TYPE_ALL_LIST } + /** + * Media types in the order Grails reads them, which keeps Spring MVC's order but for the types with the {@code +xml} + * suffix of the quality of the XML type, the first {@code application/xml} or {@code text/xml}: they come ahead of + * it, as the more specific types, each one later in the header in front of those before it, as Grails 9 orders them. + * + * @param mediaTypes the media types in Spring MVC's order + * @return the media types in the order Grails reads them + * @since 9.0 + */ + static List preferringSuffixedXml(List mediaTypes) { + int xml = mediaTypes.findIndexOf { MediaType mediaType -> + mediaType.type == 'application' && mediaType.subtype == 'xml' || mediaType.type == 'text' && mediaType.subtype == 'xml' + } + if (xml < 0) { + return mediaTypes + } + double quality = mediaTypes[xml].qualityValue + List ordered = new ArrayList<>(mediaTypes) + for (MediaType mediaType in mediaTypes.subList(xml + 1, mediaTypes.size())) { + if (mediaType.subtypeSuffix?.equalsIgnoreCase('xml') && mediaType.qualityValue >= quality) { + ordered.remove(mediaType) + ordered.add(xml, mediaType) + } + } + return ordered + } + /** * The configured MIME types media types stand for, in the order of the media types, each once, with the parameters, * such as the quality, of the first that stands for it; and a wildcard no type is configured with the name of, such as diff --git a/grails-mimetypes/src/test/groovy/org/grails/web/mime/FormatNegotiationComparisonSpec.groovy b/grails-mimetypes/src/test/groovy/org/grails/web/mime/FormatNegotiationComparisonSpec.groovy index 7c5e63e836b..ad7d002b1a5 100644 --- a/grails-mimetypes/src/test/groovy/org/grails/web/mime/FormatNegotiationComparisonSpec.groovy +++ b/grails-mimetypes/src/test/groovy/org/grails/web/mime/FormatNegotiationComparisonSpec.groovy @@ -155,7 +155,7 @@ class FormatNegotiationComparisonSpec extends Specification { 'defaults | Accept: application/soap+xml | withFormat(html, json, xml): html -> xml', 'defaults | Accept: application/soap+xml | withFormat(json, xml, *): * -> xml', 'defaults | Accept: application/soap+xml | withFormat(pdf, html): pdf -> null', - 'defaults | Accept: application/xml, application/atom+xml | response.format: atom -> xml', + 'defaults | Accept: application/xml, application/atom+xml | Spring MVC: [application/xml, application/atom+xml] -> [application/atom+xml, application/xml]', 'defaults | Accept: image/png | response.format: all -> null', 'defaults | Accept: image/png | withFormat(html, json, xml): html -> null', 'defaults | Accept: image/png | withFormat(pdf, html): pdf -> null', @@ -190,7 +190,7 @@ class FormatNegotiationComparisonSpec extends Specification { 'merged vendor type | Accept: application/soap+xml | withFormat(html, json, xml): html -> xml', 'merged vendor type | Accept: application/soap+xml | withFormat(json, xml, *): * -> xml', 'merged vendor type | Accept: application/soap+xml | withFormat(pdf, html): pdf -> null', - 'merged vendor type | Accept: application/xml, application/atom+xml | response.format: atom -> xml', + 'merged vendor type | Accept: application/xml, application/atom+xml | Spring MVC: [application/xml, application/atom+xml] -> [application/atom+xml, application/xml]', 'merged vendor type | Accept: image/png | response.format: all -> null', 'merged vendor type | Accept: image/png | withFormat(html, json, xml): html -> null', 'merged vendor type | Accept: image/png | withFormat(pdf, html): pdf -> null', @@ -231,6 +231,7 @@ class FormatNegotiationComparisonSpec extends Specification { 'without all | Accept: application/soap+xml | withFormat(html, json, xml): html -> xml', 'without all | Accept: application/soap+xml | withFormat(json, xml, *): * -> xml', 'without all | Accept: application/soap+xml | withFormat(pdf, html): pdf -> null', + 'without all | Accept: application/xml, application/atom+xml | Spring MVC: [application/xml, application/atom+xml] -> [application/atom+xml, application/xml]', 'without all | Accept: application/json;q=0, */*;q=0.1 | response.format: json -> all', 'without all | Accept: application/json;q=0, */*;q=0.1 | withFormat(html, json, xml): json -> html', 'without all | Accept: application/json;q=0, */*;q=0.1 | withFormat(json, xml, *): json -> *', @@ -243,10 +244,9 @@ class FormatNegotiationComparisonSpec extends Specification { 'without all | Accept: application/json;q=abc | withFormat(json, xml, *): json -> *', 'without all | Accept: application/json, format=xml | Spring MVC: [application/json] -> [text/xml, application/xml, application/*+xml]', 'without all | Accept: application/json, format=html | Spring MVC: [application/json] -> [text/html, application/xhtml+xml]', - 'without all | Accept: application/json, format=all | response.format: html -> null', + 'without all | Accept: application/json, format=all | response.format: html -> json', 'without all | Accept: application/json, format=all | withFormat(html, json, xml): html -> json', 'without all | Accept: application/json, format=all | withFormat(pdf, html): html -> null', - 'without all | Accept: application/json, format=all | Spring MVC: [application/json] -> not acceptable', 'without all | Accept: application/json, format=unknown | response.format: html -> null', 'without all | Accept: application/json, format=unknown | withFormat(html, json, xml): html -> json', 'without all | Accept: application/json, format=unknown | withFormat(pdf, html): html -> null', diff --git a/grails-mimetypes/src/test/groovy/org/grails/web/mime/SpringFormatNegotiationSpec.groovy b/grails-mimetypes/src/test/groovy/org/grails/web/mime/SpringFormatNegotiationSpec.groovy index 1c67f3f7e9e..2b57cce7138 100644 --- a/grails-mimetypes/src/test/groovy/org/grails/web/mime/SpringFormatNegotiationSpec.groovy +++ b/grails-mimetypes/src/test/groovy/org/grails/web/mime/SpringFormatNegotiationSpec.groovy @@ -222,7 +222,7 @@ class SpringFormatNegotiationSpec extends Specification { 'application/problem+json' || ['json'] 'application/vnd.api+json, application/xml' || ['json', 'xml'] 'application/soap+xml' || ['xml'] - 'application/xml, application/atom+xml' || ['xml', 'atom'] + 'application/xml, application/atom+xml' || ['atom', 'xml'] 'text/xml;q=0.5, application/xml;q=0.9, application/json' || ['json', 'xml', 'xml'] 'image/png' || [] 'application/json;q=abc' || [] @@ -291,6 +291,26 @@ class SpringFormatNegotiationSpec extends Specification { manager().resolveMediaTypes(new ServletWebRequest(request)) == [MediaType.APPLICATION_JSON] } + void 'a type with the +xml suffix comes ahead of the XML type of equal quality, for Grails and for what Spring MVC writes: #accept'() { + given: + start((Settings.MIME_NEGOTIATION_SPRING): true) + def request = request('Accept': accept) + handledBy(request, urlMapping()) + + expect: + GrailsWebRequest.lookup().currentResponse.mimeTypes*.extension == formats + manager().resolveMediaTypes(new ServletWebRequest(request))*.toString() == resolved + + where: + accept || formats | resolved + 'application/xml, application/atom+xml' || ['atom', 'xml'] | ['application/atom+xml', 'application/xml'] + 'text/xml, application/json, application/atom+xml' || ['atom', 'xml', 'json'] | ['application/atom+xml', 'text/xml', 'application/json'] + 'application/xml, application/rss+xml, application/atom+xml' || ['atom', 'rss', 'xml'] | ['application/atom+xml', 'application/rss+xml', 'application/xml'] + 'application/xml, application/atom+xml;q=0.5' || ['xml', 'atom'] | ['application/xml', 'application/atom+xml;q=0.5'] + 'application/atom+xml, application/xml' || ['atom', 'xml'] | ['application/atom+xml', 'application/xml'] + 'application/json, application/atom+xml' || ['json', 'atom'] | ['application/json', 'application/atom+xml'] + } + void 'a wildcard is of the all format, which withFormat answers with the first block compatible with it: #result for #accept'() { given: start((Settings.MIME_NEGOTIATION_SPRING): true) From 54de0e0604de03aa28032b2f8823c610087e7fe9 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Sun, 15 Nov 2026 08:16:43 -0800 Subject: [PATCH 13/21] Leave ?format=all to the Accept header under Spring MVC parameter negotiation With spring.mvc.contentnegotiation.favor-parameter, Spring MVC's parameter negotiation reads the format parameter, as Grails does. Grails left the all format to the Accept header, and the parameter strategy then read the same parameter again and found all not acceptable: ?format=all with Accept: application/json answered 406 to respond and to what Spring MVC writes for the action. For a request a URL mapping handles, Grails now reads the format parameter in place of that strategy, so all is left to the Accept header; a Spring MVC endpoint still reads it with Spring MVC's parameter negotiation. --- .../guide/theWebLayer/contentNegotiation.adoc | 4 +- .../GrailsContentNegotiationManager.groovy | 33 ++++++++++++- .../GrailsContentNegotiationStrategy.groovy | 20 +++++++- .../mime/SpringFormatNegotiationSpec.groovy | 49 ++++++++++++++++++- .../SpringFormatNegotiationRespondSpec.groovy | 35 +++++++++++++ 5 files changed, 135 insertions(+), 6 deletions(-) diff --git a/grails-doc/src/en/guide/theWebLayer/contentNegotiation.adoc b/grails-doc/src/en/guide/theWebLayer/contentNegotiation.adoc index e939ecc2f0a..2cd642f3bf5 100644 --- a/grails-doc/src/en/guide/theWebLayer/contentNegotiation.adoc +++ b/grails-doc/src/en/guide/theWebLayer/contentNegotiation.adoc @@ -305,7 +305,9 @@ that accepts any type, with the `all` format. * The `format` parameter and a URL extension name the format, ahead of the `Accept` header, as before. The first value of the parameter counts, as for Spring MVC; a format no type is configured for is not acceptable, where the Grails rules answer in the first configured format; and the `all` format, which is any type whether or not `grails.mime.types` lists -it, leaves the format to the `Accept` header. +it, leaves the format to the `Accept` header. Where `spring.mvc.contentnegotiation.favor-parameter` has Spring MVC read +the `format` parameter too, Grails reads it in its place for a request a URL mapping handles, so `?format=all` is left +to the `Accept` header there as well, while a Spring MVC endpoint reads it as Spring MVC does. * `grails.mime.use.accept.header` and `grails.mime.disable.accept.header.*` ignore the `Accept` header as before. * The `format` parameter, the URL extension and the `Accept` header settings also decide what Spring MVC writes for a request a URL mapping handles, so that it is in the format Grails resolves for the request: an action that returns a diff --git a/grails-mimetypes/src/main/groovy/org/grails/web/mime/GrailsContentNegotiationManager.groovy b/grails-mimetypes/src/main/groovy/org/grails/web/mime/GrailsContentNegotiationManager.groovy index 7a0cc525577..4b3d20b79ca 100644 --- a/grails-mimetypes/src/main/groovy/org/grails/web/mime/GrailsContentNegotiationManager.groovy +++ b/grails-mimetypes/src/main/groovy/org/grails/web/mime/GrailsContentNegotiationManager.groovy @@ -22,17 +22,22 @@ import java.util.function.Supplier import groovy.transform.CompileStatic +import jakarta.servlet.http.HttpServletRequest + import org.springframework.http.MediaType +import org.springframework.web.HttpMediaTypeNotAcceptableException import org.springframework.web.accept.ContentNegotiationManager import org.springframework.web.accept.ContentNegotiationStrategy import org.springframework.web.accept.HeaderContentNegotiationStrategy import org.springframework.web.accept.MediaTypeFileExtensionResolver +import org.springframework.web.context.request.NativeWebRequest /** * Spring MVC's content negotiation manager with {@code grails.mime.negotiation.spring}: its strategies, after the one * that resolves the format a request a URL mapping handles names, and with the {@code Accept} header read by one that - * ignores it for such a request where the {@code grails.mime} settings say so. Any other request is negotiated as by - * Spring MVC's manager, whose formats and file extensions it answers with. + * ignores it for such a request where the {@code grails.mime} settings say so, and without Spring MVC's parameter + * negotiation of the {@code format} parameter, which the first strategy reads for it. Any other request is negotiated as + * by Spring MVC's manager, whose formats and file extensions it answers with. * * @since 9.0 */ @@ -57,6 +62,30 @@ class GrailsContentNegotiationManager extends ContentNegotiationManager { return springManager } + /** + * Resolves the media types of a request as Spring MVC's manager does, with its strategies in their order, but for a + * request a URL mapping handles without Spring MVC's parameter negotiation of the {@code format} parameter, which the + * first strategy has read: it would read a format Spring MVC does not know, such as {@code all}, again, and find the + * request not acceptable. + */ + @Override + List resolveMediaTypes(NativeWebRequest request) throws HttpMediaTypeNotAcceptableException { + HttpServletRequest servletRequest = request.getNativeRequest(HttpServletRequest) + if (servletRequest == null || !GrailsContentNegotiationStrategy.handlesRequest(servletRequest)) { + return super.resolveMediaTypes(request) + } + for (ContentNegotiationStrategy strategy in strategies) { + if (GrailsContentNegotiationStrategy.readsFormatParameter(strategy)) { + continue + } + List mediaTypes = strategy.resolveMediaTypes(request) + if (mediaTypes != MEDIA_TYPE_ALL_LIST) { + return mediaTypes + } + } + return MEDIA_TYPE_ALL_LIST + } + @Override void addFileExtensionResolvers(MediaTypeFileExtensionResolver... resolvers) { springManager.addFileExtensionResolvers(resolvers) diff --git a/grails-mimetypes/src/main/groovy/org/grails/web/mime/GrailsContentNegotiationStrategy.groovy b/grails-mimetypes/src/main/groovy/org/grails/web/mime/GrailsContentNegotiationStrategy.groovy index 00b6166eecf..dc3d08d3aff 100644 --- a/grails-mimetypes/src/main/groovy/org/grails/web/mime/GrailsContentNegotiationStrategy.groovy +++ b/grails-mimetypes/src/main/groovy/org/grails/web/mime/GrailsContentNegotiationStrategy.groovy @@ -35,6 +35,7 @@ import org.springframework.web.HttpMediaTypeNotAcceptableException import org.springframework.web.accept.ContentNegotiationManager import org.springframework.web.accept.ContentNegotiationStrategy import org.springframework.web.accept.HeaderContentNegotiationStrategy +import org.springframework.web.accept.ParameterContentNegotiationStrategy import org.springframework.web.context.request.ServletWebRequest import org.springframework.web.context.support.WebApplicationContextUtils import org.springframework.web.servlet.HandlerMapping @@ -296,6 +297,21 @@ class GrailsContentNegotiationStrategy { return request.getAttribute(HandlerMapping.BEST_MATCHING_HANDLER_ATTRIBUTE) instanceof UrlMappingInfo } + /** + * Whether a strategy of Spring MVC's manager reads the parameter Grails reads the format a request names from, as + * the parameter negotiation {@code spring.mvc.contentnegotiation.favor-parameter} enables does by default: Grails + * reads it on its own, ahead of Spring MVC's strategies, for the requests a URL mapping handles, so that a format + * Spring MVC does not know, such as {@code all}, is not read again. + * + * @param strategy a strategy of Spring MVC's manager + * @return whether it reads the {@code format} parameter + * @since 9.0 + */ + static boolean readsFormatParameter(ContentNegotiationStrategy strategy) { + return strategy instanceof ParameterContentNegotiationStrategy && + ((ParameterContentNegotiationStrategy) strategy).parameterName == FORMAT_PARAMETER + } + /** * The strategy that resolves the formats of a request: that of the application's {@code MimeTypesConfiguration}, or, * in a context without it, such as one a test builds by hand, one built for the request from the application's @@ -327,7 +343,7 @@ class GrailsContentNegotiationStrategy { /** * The media types Spring MVC's content negotiation manager resolves for a request, in its order, without the format - * the request names, which Grails resolves on its own, and with its {@code Accept} header ignored where the + * the request names, which Grails resolves on its own, also where Spring MVC's parameter negotiation reads it, and with its {@code Accept} header ignored where the * {@code grails.mime} settings ignore it, whether or not a URL mapping handles the request. * * @return the media types, or {@code null} where the manager finds the request not acceptable, as for an @@ -341,7 +357,7 @@ class GrailsContentNegotiationStrategy { ServletWebRequest webRequest = new ServletWebRequest(request) try { for (ContentNegotiationStrategy strategy in strategies) { - if (strategy instanceof GrailsFormatContentNegotiationStrategy || + if (strategy instanceof GrailsFormatContentNegotiationStrategy || readsFormatParameter(strategy) || (acceptHeaderIgnored && strategy instanceof HeaderContentNegotiationStrategy)) { continue } diff --git a/grails-mimetypes/src/test/groovy/org/grails/web/mime/SpringFormatNegotiationSpec.groovy b/grails-mimetypes/src/test/groovy/org/grails/web/mime/SpringFormatNegotiationSpec.groovy index 2b57cce7138..2cb13b1d2f8 100644 --- a/grails-mimetypes/src/test/groovy/org/grails/web/mime/SpringFormatNegotiationSpec.groovy +++ b/grails-mimetypes/src/test/groovy/org/grails/web/mime/SpringFormatNegotiationSpec.groovy @@ -387,6 +387,39 @@ class SpringFormatNegotiationSpec extends Specification { GrailsWebRequest.lookup().currentResponse.format == 'xml' } + void "a format parameter of all, which Spring MVC's parameter negotiation of the format parameter does not know, leaves the format to the Accept header"() { + given: 'parameter negotiation on the format parameter, as spring.mvc.contentnegotiation.favor-parameter enables it' + start((Settings.MIME_NEGOTIATION_SPRING): true, (ParameterConfiguration.ENABLED): true, (ParameterConfiguration.NAME): 'format') + def request = request('Accept': 'application/json') + request.addParameter('format', 'all') + handledBy(request, urlMapping()) + + expect: + GrailsWebRequest.lookup().currentResponse.format == 'json' + GrailsWebRequest.lookup().currentResponse.mimeTypesFormatAware*.extension == ['json'] + GrailsWebRequest.lookup().currentResponse.mimeTypes*.extension == ['json'] + manager().resolveMediaTypes(new ServletWebRequest(request)) == [MediaType.APPLICATION_JSON] + } + + void "Spring MVC's parameter negotiation of the format parameter still answers #format for an endpoint, as it does without the setting"() { + given: + start((Settings.MIME_NEGOTIATION_SPRING): true, (ParameterConfiguration.ENABLED): true, (ParameterConfiguration.NAME): 'format') + def request = request('Accept': 'application/json') + request.addParameter('format', format) + handledBy(request, endpoint()) + + when: + def resolved = resolve(request) + + then: + resolved == expected + + where: + format || expected + 'xml' || [MediaType.APPLICATION_XML] + 'all' || 'not acceptable' + } + void 'the Content-Type #contentType is the request format #format'() { given: start((Settings.MIME_NEGOTIATION_SPRING): true) @@ -475,6 +508,15 @@ class SpringFormatNegotiationSpec extends Specification { context.getBean(GrailsContentNegotiationStrategy.MVC_CONTENT_NEGOTIATION_MANAGER, ContentNegotiationManager) } + private Object resolve(MockHttpServletRequest request) { + try { + manager().resolveMediaTypes(new ServletWebRequest(request)) + } + catch (HttpMediaTypeNotAcceptableException ignored) { + 'not acceptable' + } + } + private MockHttpServletRequest request(Map headers) { def request = new MockHttpServletRequest(context.servletContext) headers.each { String name, String value -> request.addHeader(name, value) } @@ -541,16 +583,21 @@ class SpringFormatNegotiationSpec extends Specification { static final String ENABLED = 'test.parameter.negotiation' + static final String NAME = 'test.parameter.negotiation.name' + private final boolean enabled + private final String name + ParameterConfiguration(ConfigurableEnvironment environment) { enabled = environment.getProperty(ENABLED, Boolean, false) + name = environment.getProperty(NAME, 'mediaType') } @Override void configureContentNegotiation(ContentNegotiationConfigurer configurer) { if (enabled) { - configurer.favorParameter(true).parameterName('mediaType') + configurer.favorParameter(true).parameterName(name) } } } diff --git a/grails-test-suite-web/src/test/groovy/grails/rest/web/SpringFormatNegotiationRespondSpec.groovy b/grails-test-suite-web/src/test/groovy/grails/rest/web/SpringFormatNegotiationRespondSpec.groovy index a6a5118f31b..8d44f1fd709 100644 --- a/grails-test-suite-web/src/test/groovy/grails/rest/web/SpringFormatNegotiationRespondSpec.groovy +++ b/grails-test-suite-web/src/test/groovy/grails/rest/web/SpringFormatNegotiationRespondSpec.groovy @@ -184,6 +184,41 @@ class SpringFormatNegotiationWithoutAllRespondSpec extends Specification impleme } } +/** + * With {@code grails.mime.negotiation.spring} and Spring MVC's parameter negotiation of the {@code format} parameter, + * which {@code spring.mvc.contentnegotiation.favor-parameter} enables, {@code respond} answers the format the parameter + * names, and the {@code all} format with the {@code Accept} header. + */ +class SpringFormatNegotiationParameterRespondSpec extends Specification implements ControllerUnitTest { + + Closure doWithConfig() { + { config -> + config[Settings.WEB_RENDERING_JSON_SPRING] = true + config[Settings.MIME_NEGOTIATION_SPRING] = true + config['spring.mvc.contentnegotiation.favor-parameter'] = true + } + } + + void 'a format parameter of #format answers with #status #contentType'() { + given: + request.addHeader('Accept', 'application/json') + request.addParameter('format', format) + + when: + controller.respond([title: 'Grails'], formats: ['json', 'xml']) + + then: + response.status == status + (response.contentType ?: '').startsWith(contentType) + + where: + format || status | contentType + 'all' || 200 | 'application/json' + 'xml' || 200 | 'text/xml' + 'unknown' || 406 | '' + } +} + /** * Without {@code grails.mime.negotiation.spring}, the Grails 9 rules resolve the format {@code respond} answers in. */ From 4b56419494b3a364dcc85f79e0bd1e0d4fb06b84 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Tue, 17 Nov 2026 07:59:33 -0800 Subject: [PATCH 14/21] Point What's New at the renumbered upgrade section --- grails-doc/src/en/guide/introduction/whatsNew.adoc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/grails-doc/src/en/guide/introduction/whatsNew.adoc b/grails-doc/src/en/guide/introduction/whatsNew.adoc index 83708c70168..7d20d354787 100644 --- a/grails-doc/src/en/guide/introduction/whatsNew.adoc +++ b/grails-doc/src/en/guide/introduction/whatsNew.adoc @@ -174,7 +174,7 @@ With `grails.mime.negotiation.spring: true`, which Grails 10 makes the default, `ResponseEntity` it returns. See xref:theWebLayer#springFormatNegotiation[Resolving Formats with Spring MVC Content Negotiation]. -See xref:upgrading#upgrading90x[Upgrading from Grails 8 to Grails 9], sections 4 to 11, 13 to 16 and 22. +See xref:upgrading#upgrading90x[Upgrading from Grails 8 to Grails 9], sections 4 to 11, 13 to 16 and 25. ==== Hibernate 7 Criteria Queries Can Be Extended From 9e031ee6054251f322db4b1ef6eacb2ff531f253 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Tue, 17 Nov 2026 11:43:11 -0800 Subject: [PATCH 15/21] Point the content negotiation guide at upgrade section 25 The merge of 9.0.x renumbered the upgrade notes of grails.mime.negotiation.spring to section 25, which the guide still gave as section 22. The grails-9-upgrade skill now lists the setting with the other opt-in settings Grails 10 makes the default, and the answers it changes. --- .../en/guide/theWebLayer/contentNegotiation.adoc | 2 +- .../skills/grails-9-upgrade/SKILL.md | 14 +++++++++++++- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/grails-doc/src/en/guide/theWebLayer/contentNegotiation.adoc b/grails-doc/src/en/guide/theWebLayer/contentNegotiation.adoc index 2cd642f3bf5..9de2792e674 100644 --- a/grails-doc/src/en/guide/theWebLayer/contentNegotiation.adoc +++ b/grails-doc/src/en/guide/theWebLayer/contentNegotiation.adoc @@ -347,7 +347,7 @@ type is configured for in the first configured format |Dropped: such a request, and one whose `Accept` header Spring cannot read, is not acceptable. |=== -Section 22 of xref:upgrading#upgrading90x[Upgrading from Grails 8 to Grails 9] lists how each answer changes. +Section 25 of xref:upgrading#upgrading90x[Upgrading from Grails 8 to Grails 9] lists how each answer changes. ==== Testing Content Negotiation diff --git a/grails-skills/upgrade-guide-9/skills/grails-9-upgrade/SKILL.md b/grails-skills/upgrade-guide-9/skills/grails-9-upgrade/SKILL.md index ce4817a689f..1172635fb72 100644 --- a/grails-skills/upgrade-guide-9/skills/grails-9-upgrade/SKILL.md +++ b/grails-skills/upgrade-guide-9/skills/grails-9-upgrade/SKILL.md @@ -26,7 +26,7 @@ Activate this skill when: - Reviewing a Grails 9 upgrade branch or pull request. - Fixing tests, build failures, runtime failures, or behavior changes after moving from Grails 8.x to Grails 9. - Deciding whether an application keeps or excludes `grails-xml`. -- Turning on `grails.web.rendering.json.spring`, `grails.converters.json.legacy: false`, `grails.databinding.json.jackson`, `grails.exceptionresolver.springHandlers` or `grails.controllers.responseBody`, and checking what changes. +- Turning on `grails.web.rendering.json.spring`, `grails.converters.json.legacy: false`, `grails.databinding.json.jackson`, `grails.exceptionresolver.springHandlers`, `grails.controllers.responseBody` or `grails.mime.negotiation.spring`, and checking what changes. - Replacing `JSON.createNamedConfig(...)`, `JSON.use(...)` or marshallers that customize `respond` with Jackson serializers and the `NamedJsonConfigurationRegistry`. - Fixing web unit tests (`ControllerUnitTest`, `TagLibUnitTest`, `UrlMappingsUnitTest`, `JsonViewUnitTest`) that fail after the upgrade. - Porting code that uses RxGORM, `grails-async-rxjava`, `grails-async-rxjava2`, `grails-events-rxjava`, or `grails-events-rxjava2` to RxJava 3. @@ -161,6 +161,7 @@ XML conversion, XML request-body binding, and the XML, Atom, HAL XML and Vnd.Err | `grails.web.rendering.xml.spring` | XML that `respond` writes for ordinary beans | `false` | unchanged until Grails 11 removes legacy XML conversion | | `grails.exceptionresolver.springHandlers` | Exceptions actions throw, resolved by Spring MVC `@ExceptionHandler` methods | `false` | `true` in Grails 10 | | `grails.controllers.responseBody` | The values of actions annotated `@ResponseBody`, written by Spring MVC as the body | `false` | `true` in Grails 10 | +| `grails.mime.negotiation.spring` | `request.format`, `response.format`, `withFormat` and the format `respond` writes in, resolved with Spring MVC's content negotiation manager | `false` | `true` in Grails 10 | - Grails 10 changes the three JSON settings together, so that `respond`, `render ... as JSON`, `request.JSON` and data binding write and read JSON with the same mapper. Test them together. At the least, set `grails.converters.json.legacy: false` and `grails.databinding.json.jackson: true` together, or `request.JSON` and data binding accept different JSON. - Grails 9 logs a warning while a legacy path is used: once when the legacy `respond` path renders, at startup for `JsonSlurper` request binding, and at startup while `grails.converters.json.legacy` is unset. Setting `grails.converters.json.legacy` to either value turns its warning off. @@ -336,6 +337,17 @@ The Grails HAL JSON renderers remain available through explicit renderer registr - A renderer or binding source creator registered for an interface of `java.lang.Class`, such as `Serializable`, no longer matches every class. - The MIME types and the `grails.mime.use.accept.header` and `grails.mime.disable.accept.header.*` settings live in the application context instead of static fields. Remove test code that reset those fields or called `HttpServletResponseExtension.loadMimeTypeConfig`, and set the settings in a spec's `doWithConfig`, since they are read once for each application context. A subclass of `DefaultAcceptHeaderParser` that overrode `createMimeTypeAndAddToList` must take the requested `MimeType` now. +### Opt Into Spring MVC Content Negotiation for Grails Formats + +With `grails.mime.negotiation.spring: true`, which Grails 10 makes the default, Grails formats are resolved with Spring MVC's content negotiation manager, and the `format` parameter, URL extensions and the `grails.mime` `Accept` settings also decide what Spring MVC writes for an action. Before turning it on, check these in functional tests: + +- `Accept: */*, application/json` is `json`, where it is `all` without the setting: a more specific type comes ahead of a wildcard of equal quality. A `+xml` type still comes ahead of the XML type of equal quality. +- A type with the `+json` or `+xml` suffix that no configured type names, such as `application/merge-patch+json`, is the `json` or `xml` format, in `Accept` and in `Content-Type`, so data binding reads such a body as JSON. +- A request that accepts no configured type, such as `Accept: image/png` alone, or whose `Accept` header Spring cannot read, has no format: `response.format` and `response.mimeType` are `null`, `respond` answers `406` and `withFormat` runs its `*` block, or none. Make code that reads them allow for `null`. +- A format parameter or URL extension no type is configured for is not acceptable, where it was answered in the first configured format. `?format=all` leaves the format to the `Accept` header. +- A `ResponseEntity`, `ProblemDetail` or other value Spring MVC writes for an action follows the URL extension and the format parameter: `/book/show/1.json` is JSON whatever the `Accept` header says, and a map at `/book/show/1.html` answers `406`. +- A wildcard such as `text/*` selects the first `withFormat` block, or the first format of the action, with a type compatible with it. + ## Web Unit Tests - `ControllerUnitTest`, `TagLibUnitTest` and the other web test traits always include the `restResponder` plugin, even when a spec overrides `getIncludePlugins()`. They also register JSON conversion beans with Boot's Jackson configuration, Spring MVC's message converters, the `mvcContentNegotiationManager` and `requestMappingHandlerAdapter` beans unless the spec declares beans of those names, and the `grails-xml` beans when that module is on the test classpath. Update specs that assert on the beans of their context. From e17f6527525dc7106f25e8bc74d34d26aac0bdea Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Wed, 18 Nov 2026 14:09:59 -0800 Subject: [PATCH 16/21] Link the content negotiation upgrade notes by anchor What's New still named section 25 for the upgrade notes of grails.mime.negotiation.spring, which 9.0.x gave to classes that are not multi-tenant; it now names section 26. The notes get the anchor upgradingSpringFormatNegotiation, which the content negotiation guide links to in place of a section number, so the next renumbering cannot leave it stale, and What's New links to the guide section with <<...>>, so readers of the single-page guide stay on the page. The grails-upgrade skill names no section numbers, so it needs no change. --- grails-doc/src/en/guide/introduction/whatsNew.adoc | 5 ++--- grails-doc/src/en/guide/theWebLayer/contentNegotiation.adoc | 3 ++- grails-doc/src/en/guide/upgrading/upgrading90x.adoc | 1 + 3 files changed, 5 insertions(+), 4 deletions(-) diff --git a/grails-doc/src/en/guide/introduction/whatsNew.adoc b/grails-doc/src/en/guide/introduction/whatsNew.adoc index 8562f59a7ab..61964a48f47 100644 --- a/grails-doc/src/en/guide/introduction/whatsNew.adoc +++ b/grails-doc/src/en/guide/introduction/whatsNew.adoc @@ -171,10 +171,9 @@ With `grails.mime.negotiation.spring: true`, which Grails 10 makes the default, `withFormat` and the format `respond` writes in are resolved with Spring MVC's content negotiation manager, so that the `spring.mvc.contentnegotiation.*` settings apply to them, and the `format` parameter, URL extensions and the `grails.mime` settings of the `Accept` header decide what Spring MVC writes for an action too, such as a -`ResponseEntity` it returns. See xref:theWebLayer#springFormatNegotiation[Resolving Formats with Spring MVC Content -Negotiation]. +`ResponseEntity` it returns. See <>. -See xref:upgrading#upgrading90x[Upgrading from Grails 8 to Grails 9], sections 4 to 11, 13 to 16 and 25. +See xref:upgrading#upgrading90x[Upgrading from Grails 8 to Grails 9], sections 4 to 11, 13 to 16 and 26. ==== Hibernate 7 Criteria Queries Can Be Extended diff --git a/grails-doc/src/en/guide/theWebLayer/contentNegotiation.adoc b/grails-doc/src/en/guide/theWebLayer/contentNegotiation.adoc index b2e84961b73..2d2d5187103 100644 --- a/grails-doc/src/en/guide/theWebLayer/contentNegotiation.adoc +++ b/grails-doc/src/en/guide/theWebLayer/contentNegotiation.adoc @@ -347,7 +347,8 @@ type is configured for in the first configured format |Dropped: such a request, and one whose `Accept` header Spring cannot read, is not acceptable. |=== -Section 26 of xref:upgrading#upgrading90x[Upgrading from Grails 8 to Grails 9] lists how each answer changes. +<>, in the guide to +upgrading from Grails 8 to Grails 9, lists how each answer changes. ==== Testing Content Negotiation diff --git a/grails-doc/src/en/guide/upgrading/upgrading90x.adoc b/grails-doc/src/en/guide/upgrading/upgrading90x.adoc index 26476cea876..e5da07f9927 100644 --- a/grails-doc/src/en/guide/upgrading/upgrading90x.adoc +++ b/grails-doc/src/en/guide/upgrading/upgrading90x.adoc @@ -1484,6 +1484,7 @@ With GORM for MongoDB, a class that is not multi-tenant and was saved inside a t Data services choose their transaction manager in code generated at compile time, so a data service compiled against an earlier release keeps following the tenant until it is compiled again. +[[upgradingSpringFormatNegotiation]] ==== 26. Opt Into Spring MVC Content Negotiation for Grails Formats Set `grails.mime.negotiation.spring: true` to resolve `request.format`, `response.format`, `withFormat` and the format From c903885e6e517988215359dd24f819caafd0dcdd Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Wed, 18 Nov 2026 14:11:09 -0800 Subject: [PATCH 17/21] Test a text Spring MVC writes in the format of its URL extension as text /springWritten/text.json answered the plain string Grails labelled application/json, which reads as if JSON-labelled text were the intent. The spec now asks for /springWritten/text.text with Accept: application/json and expects text/plain: the URL extension still wins over the Accept header, and the body is what its type says. --- .../SpringFormatNegotiationSpec.groovy | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/grails-test-examples/spring-format-negotiation/src/integration-test/groovy/springformatnegotiation/SpringFormatNegotiationSpec.groovy b/grails-test-examples/spring-format-negotiation/src/integration-test/groovy/springformatnegotiation/SpringFormatNegotiationSpec.groovy index b261db0a940..e74d5168d17 100644 --- a/grails-test-examples/spring-format-negotiation/src/integration-test/groovy/springformatnegotiation/SpringFormatNegotiationSpec.groovy +++ b/grails-test-examples/spring-format-negotiation/src/integration-test/groovy/springformatnegotiation/SpringFormatNegotiationSpec.groovy @@ -39,9 +39,9 @@ class SpringFormatNegotiationSpec extends Specification implements HttpClientSup http('/springWritten/entity.json', Accept: 'text/html').assertStatus(200).contentType.startsWith('application/json') } - void 'a text Spring MVC writes for an action is labelled with the format of its URL extension'() { + void 'a text Spring MVC writes for an action is in the format of its URL extension, whatever the Accept header asks for'() { expect: - http('/springWritten/text.json', Accept: 'text/plain').assertStatus(200).contentType.startsWith('application/json') + http('/springWritten/text.text', Accept: 'application/json').assertStatus(200).contentType.startsWith('text/plain') } void 'a request that names a format no type is configured for is not acceptable'() { From a7ae6fcd8604a9b19cf9d44fdb93ec8219be3c3c Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Wed, 18 Nov 2026 21:04:23 -0800 Subject: [PATCH 18/21] Write a format only Spring MVC maps in the type it maps it to For a request a URL mapping handles, Grails reads the format parameter and the URL extension in place of Spring MVC's parameter strategy, and rejected a format grails.mime.types does not list before Spring MVC could map it: with spring.mvc.contentnegotiation.media-types.plain: text/plain, ?format=plain or .plain with Accept: application/json answered 406 for a ResponseEntity the action returns. A format grails.mime.types does not list is now the type Spring MVC's content negotiation manager maps it to, with or without favor-parameter, and only a format neither maps is not acceptable. A format Grails configures keeps its own types, and respond still answers 406 for a format only Spring MVC maps, since Grails has no type of it to render. The guide, the upgrade notes and the grails-upgrade skill say so. --- .../guide/theWebLayer/contentNegotiation.adoc | 9 ++-- .../src/en/guide/upgrading/upgrading90x.adoc | 6 ++- .../GrailsContentNegotiationStrategy.groovy | 26 ++++++++++-- ...ilsFormatContentNegotiationStrategy.groovy | 7 +++- .../mime/SpringFormatNegotiationSpec.groovy | 41 +++++++++++++++++++ .../upgrade/skills/grails-upgrade/SKILL.md | 2 +- .../grails-app/conf/application.yml | 4 ++ .../SpringFormatNegotiationSpec.groovy | 12 +++++- .../SpringFormatNegotiationRespondSpec.groovy | 5 ++- 9 files changed, 99 insertions(+), 13 deletions(-) diff --git a/grails-doc/src/en/guide/theWebLayer/contentNegotiation.adoc b/grails-doc/src/en/guide/theWebLayer/contentNegotiation.adoc index 2d2d5187103..77317acd7f5 100644 --- a/grails-doc/src/en/guide/theWebLayer/contentNegotiation.adoc +++ b/grails-doc/src/en/guide/theWebLayer/contentNegotiation.adoc @@ -304,7 +304,9 @@ Spring cannot read, has no format: `response.format` and `response.mimeType` are that accepts any type, with the `all` format. * The `format` parameter and a URL extension name the format, ahead of the `Accept` header, as before. The first value of the parameter counts, as for Spring MVC; a format no type is configured for is not acceptable, where the Grails rules -answer in the first configured format; and the `all` format, which is any type whether or not `grails.mime.types` lists +answer in the first configured format, but what Spring MVC writes for a format `grails.mime.types` does not list and +`spring.mvc.contentnegotiation.media-types` maps is in the type that maps it, while `respond` answers it with +`406 Not Acceptable`; and the `all` format, which is any type whether or not `grails.mime.types` lists it, leaves the format to the `Accept` header. Where `spring.mvc.contentnegotiation.favor-parameter` has Spring MVC read the `format` parameter too, Grails reads it in its place for a request a URL mapping handles, so `?format=all` is left to the `Accept` header there as well, while a Spring MVC endpoint reads it as Spring MVC does. @@ -327,8 +329,9 @@ no URL mapping handles. Each rule of Grails' negotiation becomes: |Grails rule |With `grails.mime.negotiation.spring` |The `format` parameter and URL extensions select the format -|Kept, ahead of Spring MVC's strategies, and also for what Spring MVC writes for the request. An unknown format is not -acceptable, and the `all` format leaves the choice to the `Accept` header. +|Kept, ahead of Spring MVC's strategies, and also for what Spring MVC writes for the request, which a format only +`spring.mvc.contentnegotiation.media-types` maps decides too. A format neither maps is not acceptable, and the `all` +format leaves the choice to the `Accept` header. |`grails.mime.use.accept.header` and `grails.mime.disable.accept.header.*` ignore the `Accept` header |Kept, also for what Spring MVC writes for the request. diff --git a/grails-doc/src/en/guide/upgrading/upgrading90x.adoc b/grails-doc/src/en/guide/upgrading/upgrading90x.adoc index e5da07f9927..2632ce87bd9 100644 --- a/grails-doc/src/en/guide/upgrading/upgrading90x.adoc +++ b/grails-doc/src/en/guide/upgrading/upgrading90x.adoc @@ -1520,8 +1520,10 @@ where the Grails rules answer as for a client that accepts any type, with the `a leniently. Code that reads `response.format` or `response.mimeType` must allow for `null`. * *The `format` parameter and URL extensions.* A format no type is configured for is not acceptable, to `respond`, which answers `406`, and to what Spring MVC writes, where the Grails rules answer in the first configured format; -`withFormat` answers it from the `Accept` header, as for a format it has no block for. The `all` format leaves the -format to the `Accept` header: `?format=all` with `Accept: application/json` is `json`, where it is otherwise `all`. The +`withFormat` answers it from the `Accept` header, as for a format it has no block for. A format that +`spring.mvc.contentnegotiation.media-types` maps, such as `plain: text/plain`, decides what Spring MVC writes, as +without the setting where `spring.mvc.contentnegotiation.favor-parameter` is on, while `respond` still answers `406` +for it. The `all` format leaves the format to the `Accept` header: `?format=all` with `Accept: application/json` is `json`, where it is otherwise `all`. The first value of the parameter counts. * *What Spring MVC writes for an action.* The `format` parameter and URL extensions now decide the type of a `ResponseEntity`, a `ProblemDetail` or another value Spring MVC writes for a request a URL mapping handles, where Spring diff --git a/grails-mimetypes/src/main/groovy/org/grails/web/mime/GrailsContentNegotiationStrategy.groovy b/grails-mimetypes/src/main/groovy/org/grails/web/mime/GrailsContentNegotiationStrategy.groovy index dc3d08d3aff..dd6543aca30 100644 --- a/grails-mimetypes/src/main/groovy/org/grails/web/mime/GrailsContentNegotiationStrategy.groovy +++ b/grails-mimetypes/src/main/groovy/org/grails/web/mime/GrailsContentNegotiationStrategy.groovy @@ -259,12 +259,32 @@ class GrailsContentNegotiationStrategy { } /** - * @return the media types of every configured MIME type Spring can read, which a request that names a format no type - * is configured for is not acceptable in + * The media type Spring MVC's content negotiation manager maps a format to, as {@code spring.mvc.contentnegotiation.media-types} + * maps one, for a format no type of {@code grails.mime.types} stands for, so that what Spring MVC writes for a request + * that names it is in that type, as without {@code grails.mime.negotiation.spring}. + * + * @param format the format + * @return the media type, as a list, or {@code null} where the manager maps no type to the format + * @since 9.0 + */ + List springMediaTypesOf(String format) { + MediaType mediaType = format != null ? + contentNegotiationManager?.get()?.mediaTypeMappings?.get(format.toLowerCase(Locale.ENGLISH)) : null + return mediaType != null ? [mediaType] : null + } + + /** + * @return the media types of every configured MIME type Spring can read, and of every format Spring MVC's content + * negotiation manager maps, which a request that names a format neither maps is not acceptable in * @since 9.0 */ List getConfiguredMediaTypes() { - return mediaTypes.findAll { it }.unique() as List + List configured = mediaTypes.findAll { it } as List + Map springMappings = contentNegotiationManager?.get()?.mediaTypeMappings + if (springMappings) { + configured.addAll(springMappings.values()) + } + return configured.unique() } /** diff --git a/grails-mimetypes/src/main/groovy/org/grails/web/mime/GrailsFormatContentNegotiationStrategy.groovy b/grails-mimetypes/src/main/groovy/org/grails/web/mime/GrailsFormatContentNegotiationStrategy.groovy index 9db039048b1..0ca63b474fc 100644 --- a/grails-mimetypes/src/main/groovy/org/grails/web/mime/GrailsFormatContentNegotiationStrategy.groovy +++ b/grails-mimetypes/src/main/groovy/org/grails/web/mime/GrailsFormatContentNegotiationStrategy.groovy @@ -36,7 +36,9 @@ import org.grails.web.servlet.mvc.GrailsWebRequest * names, with its {@code format} parameter or a URL extension, to the media types {@code grails.mime.types} gives it, * ahead of Spring MVC's own strategies, so that what Spring MVC writes for it is in the format Grails resolves for it. It * leaves any other request, such as one a Spring MVC endpoint handles, to them, and so a request whose format names no - * type, as the {@code all} format does. A request that names a format no type is configured for is not acceptable. + * type, as the {@code all} format does. A format no type of {@code grails.mime.types} stands for is the type Spring MVC's + * manager maps it to, as {@code spring.mvc.contentnegotiation.media-types} maps one, and a request that names a format + * neither maps is not acceptable. * * @since 9.0 */ @@ -65,7 +67,8 @@ class GrailsFormatContentNegotiationStrategy implements ContentNegotiationStrate if (format == null) { return MEDIA_TYPE_ALL_LIST } - List mediaTypes = strategy.mediaTypesOf(format.toString()) + // a format grails.mime.types configures keeps its types; any other is the type Spring MVC's manager maps it to + List mediaTypes = strategy.mediaTypesOf(format.toString()) ?: strategy.springMediaTypesOf(format.toString()) if (mediaTypes == null) { throw new HttpMediaTypeNotAcceptableException(strategy.configuredMediaTypes) } diff --git a/grails-mimetypes/src/test/groovy/org/grails/web/mime/SpringFormatNegotiationSpec.groovy b/grails-mimetypes/src/test/groovy/org/grails/web/mime/SpringFormatNegotiationSpec.groovy index 2cb13b1d2f8..65d4d459575 100644 --- a/grails-mimetypes/src/test/groovy/org/grails/web/mime/SpringFormatNegotiationSpec.groovy +++ b/grails-mimetypes/src/test/groovy/org/grails/web/mime/SpringFormatNegotiationSpec.groovy @@ -420,6 +420,38 @@ class SpringFormatNegotiationSpec extends Specification { 'all' || 'not acceptable' } + void "a format only Spring MVC's media types map is written in the type they map it to, #how"() { + given: 'plain mapped to text/plain in Spring MVC only, as spring.mvc.contentnegotiation.media-types.plain maps it' + start((Settings.MIME_NEGOTIATION_SPRING): true, (ParameterConfiguration.PLAIN): true, + (ParameterConfiguration.ENABLED): favorParameter, (ParameterConfiguration.NAME): 'format') + def request = request('Accept': 'application/json') + request.addParameter('format', format) + handledBy(request, urlMapping()) + + expect: + resolve(request) == expected + + where: + how | favorParameter | format || expected + 'without parameter negotiation' | false | 'plain' || [MediaType.TEXT_PLAIN] + 'with parameter negotiation of the format parameter' | true | 'plain' || [MediaType.TEXT_PLAIN] + 'whatever the case of the format' | false | 'PLAIN' || [MediaType.TEXT_PLAIN] + 'and a format neither maps is not acceptable' | false | 'unknown' || 'not acceptable' + 'and with parameter negotiation, still not acceptable' | true | 'unknown' || 'not acceptable' + } + + void "a format Grails configures keeps the types grails.mime.types gives it, whatever type Spring MVC's media types map it to"() { + given: + start((Settings.MIME_NEGOTIATION_SPRING): true, 'grails.mime.types': [all: '*/*', json: 'application/json', plain: 'text/csv'], + (ParameterConfiguration.PLAIN): true) + def request = request('Accept': 'application/json') + request.addParameter('format', 'plain') + handledBy(request, urlMapping()) + + expect: + resolve(request) == [MediaType.parseMediaType('text/csv')] + } + void 'the Content-Type #contentType is the request format #format'() { given: start((Settings.MIME_NEGOTIATION_SPRING): true) @@ -585,13 +617,19 @@ class SpringFormatNegotiationSpec extends Specification { static final String NAME = 'test.parameter.negotiation.name' + /** Maps the {@code plain} format to {@code text/plain}, as {@code spring.mvc.contentnegotiation.media-types.plain} does. */ + static final String PLAIN = 'test.parameter.negotiation.plain' + private final boolean enabled private final String name + private final boolean plain + ParameterConfiguration(ConfigurableEnvironment environment) { enabled = environment.getProperty(ENABLED, Boolean, false) name = environment.getProperty(NAME, 'mediaType') + plain = environment.getProperty(PLAIN, Boolean, false) } @Override @@ -599,6 +637,9 @@ class SpringFormatNegotiationSpec extends Specification { if (enabled) { configurer.favorParameter(true).parameterName(name) } + if (plain) { + configurer.mediaType('plain', MediaType.TEXT_PLAIN) + } } } } diff --git a/grails-skills/upgrade/skills/grails-upgrade/SKILL.md b/grails-skills/upgrade/skills/grails-upgrade/SKILL.md index 44a0c6b3ba2..69c42ecd510 100644 --- a/grails-skills/upgrade/skills/grails-upgrade/SKILL.md +++ b/grails-skills/upgrade/skills/grails-upgrade/SKILL.md @@ -448,7 +448,7 @@ With `grails.mime.negotiation.spring: true`, which Grails 10 makes the default, - `Accept: */*, application/json` is `json`, where it is `all` without the setting: a more specific type comes ahead of a wildcard of equal quality. A `+xml` type still comes ahead of the XML type of equal quality. - A type with the `+json` or `+xml` suffix that no configured type names, such as `application/merge-patch+json`, is the `json` or `xml` format, in `Accept` and in `Content-Type`, so data binding reads such a body as JSON. - A request that accepts no configured type, such as `Accept: image/png` alone, or whose `Accept` header Spring cannot read, has no format: `response.format` and `response.mimeType` are `null`, `respond` answers `406` and `withFormat` runs its `*` block, or none. Make code that reads them allow for `null`. -- A format parameter or URL extension no type is configured for is not acceptable, where it was answered in the first configured format. `?format=all` leaves the format to the `Accept` header. +- A format parameter or URL extension no type is configured for is not acceptable, where it was answered in the first configured format. A format only `spring.mvc.contentnegotiation.media-types` maps still decides what Spring MVC writes for an action, such as a `ResponseEntity`, but `respond` answers it with `406`. `?format=all` leaves the format to the `Accept` header. - A `ResponseEntity`, `ProblemDetail` or other value Spring MVC writes for an action follows the URL extension and the format parameter: `/book/show/1.json` is JSON whatever the `Accept` header says, and a map at `/book/show/1.html` answers `406`. - A wildcard such as `text/*` selects the first `withFormat` block, or the first format of the action, with a type compatible with it. diff --git a/grails-test-examples/spring-format-negotiation/grails-app/conf/application.yml b/grails-test-examples/spring-format-negotiation/grails-app/conf/application.yml index 4b8bc514017..f451db25241 100644 --- a/grails-test-examples/spring-format-negotiation/grails-app/conf/application.yml +++ b/grails-test-examples/spring-format-negotiation/grails-app/conf/application.yml @@ -30,3 +30,7 @@ spring: groovy: template: check-template-location: false + mvc: + contentnegotiation: + media-types: + plain: text/plain diff --git a/grails-test-examples/spring-format-negotiation/src/integration-test/groovy/springformatnegotiation/SpringFormatNegotiationSpec.groovy b/grails-test-examples/spring-format-negotiation/src/integration-test/groovy/springformatnegotiation/SpringFormatNegotiationSpec.groovy index e74d5168d17..ea570a0c924 100644 --- a/grails-test-examples/spring-format-negotiation/src/integration-test/groovy/springformatnegotiation/SpringFormatNegotiationSpec.groovy +++ b/grails-test-examples/spring-format-negotiation/src/integration-test/groovy/springformatnegotiation/SpringFormatNegotiationSpec.groovy @@ -44,7 +44,17 @@ class SpringFormatNegotiationSpec extends Specification implements HttpClientSup http('/springWritten/text.text', Accept: 'application/json').assertStatus(200).contentType.startsWith('text/plain') } - void 'a request that names a format no type is configured for is not acceptable'() { + void "a format only Spring MVC's media types map decides what Spring MVC writes for an action, by #how"() { + expect: + http(uri, Accept: 'application/json').assertStatus(200).contentType.startsWith('text/plain') + + where: + how | uri + 'the format parameter' | '/springWritten/text?format=plain' + 'the URL extension' | '/springWritten/text.plain' + } + + void 'a request that names a format neither grails.mime.types nor Spring MVC maps is not acceptable'() { expect: http('/springWritten/entity?format=unknown', Accept: 'application/json').assertStatus(406) } diff --git a/grails-test-suite-web/src/test/groovy/grails/rest/web/SpringFormatNegotiationRespondSpec.groovy b/grails-test-suite-web/src/test/groovy/grails/rest/web/SpringFormatNegotiationRespondSpec.groovy index 8d44f1fd709..7e7d0a8c1e7 100644 --- a/grails-test-suite-web/src/test/groovy/grails/rest/web/SpringFormatNegotiationRespondSpec.groovy +++ b/grails-test-suite-web/src/test/groovy/grails/rest/web/SpringFormatNegotiationRespondSpec.groovy @@ -187,7 +187,8 @@ class SpringFormatNegotiationWithoutAllRespondSpec extends Specification impleme /** * With {@code grails.mime.negotiation.spring} and Spring MVC's parameter negotiation of the {@code format} parameter, * which {@code spring.mvc.contentnegotiation.favor-parameter} enables, {@code respond} answers the format the parameter - * names, and the {@code all} format with the {@code Accept} header. + * names, and the {@code all} format with the {@code Accept} header. A format only Spring MVC's media types map is not one + * {@code respond} renders. */ class SpringFormatNegotiationParameterRespondSpec extends Specification implements ControllerUnitTest { @@ -196,6 +197,7 @@ class SpringFormatNegotiationParameterRespondSpec extends Specification implemen config[Settings.WEB_RENDERING_JSON_SPRING] = true config[Settings.MIME_NEGOTIATION_SPRING] = true config['spring.mvc.contentnegotiation.favor-parameter'] = true + config['spring.mvc.contentnegotiation.media-types.plain'] = 'text/plain' } } @@ -216,6 +218,7 @@ class SpringFormatNegotiationParameterRespondSpec extends Specification implemen 'all' || 200 | 'application/json' 'xml' || 200 | 'text/xml' 'unknown' || 406 | '' + 'plain' || 406 | '' } } From d083edaa5fe93bc0c1f080155840f04e451dfa01 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Thu, 19 Nov 2026 08:49:49 -0800 Subject: [PATCH 19/21] Look up the negotiation strategy once for each request GrailsContentNegotiationStrategy.forRequest looked the strategy up in the application context on every call, and, in a context without MimeTypesConfiguration, such as one a test builds by hand, built a new one each time. request.format, response.format, response.mimeType, withFormat and respond each call it, also without grails.mime.negotiation.spring, since the setting is only known through the strategy. The strategy is now kept as an attribute of the request it was resolved for, so each request looks it up once, for every caller, and the RestResponder trait gets no field. --- .../GrailsContentNegotiationStrategy.groovy | 15 +++++++++- .../mime/SpringFormatNegotiationSpec.groovy | 28 +++++++++++++++++++ 2 files changed, 42 insertions(+), 1 deletion(-) diff --git a/grails-mimetypes/src/main/groovy/org/grails/web/mime/GrailsContentNegotiationStrategy.groovy b/grails-mimetypes/src/main/groovy/org/grails/web/mime/GrailsContentNegotiationStrategy.groovy index dd6543aca30..9348ecf1a3b 100644 --- a/grails-mimetypes/src/main/groovy/org/grails/web/mime/GrailsContentNegotiationStrategy.groovy +++ b/grails-mimetypes/src/main/groovy/org/grails/web/mime/GrailsContentNegotiationStrategy.groovy @@ -71,6 +71,8 @@ class GrailsContentNegotiationStrategy { private static final String ALL_FORMAT = 'all' + private static final String REQUEST_STRATEGY_ATTRIBUTE = GrailsContentNegotiationStrategy.name + '.REQUEST_STRATEGY' + /** The formats a type with the structured syntax suffix of RFC 6839 of their name is a document of. */ private static final Set SUFFIX_FORMATS = Set.of('json', 'xml') @@ -335,13 +337,24 @@ class GrailsContentNegotiationStrategy { /** * The strategy that resolves the formats of a request: that of the application's {@code MimeTypesConfiguration}, or, * in a context without it, such as one a test builds by hand, one built for the request from the application's - * settings. + * settings. It is looked up once for each request, which keeps it as an attribute, so that {@code request.format}, + * {@code response.format}, {@code withFormat} and {@code respond} do not look it up again. * * @param request the request * @return the strategy * @since 9.0 */ static GrailsContentNegotiationStrategy forRequest(HttpServletRequest request) { + Object kept = request.getAttribute(REQUEST_STRATEGY_ATTRIBUTE) + if (kept instanceof GrailsContentNegotiationStrategy) { + return (GrailsContentNegotiationStrategy) kept + } + GrailsContentNegotiationStrategy strategy = lookUp(request) + request.setAttribute(REQUEST_STRATEGY_ATTRIBUTE, strategy) + return strategy + } + + private static GrailsContentNegotiationStrategy lookUp(HttpServletRequest request) { ApplicationContext applicationContext = GrailsWebRequest.lookup()?.applicationContext if (applicationContext == null && request.servletContext != null) { applicationContext = WebApplicationContextUtils.getWebApplicationContext(request.servletContext) diff --git a/grails-mimetypes/src/test/groovy/org/grails/web/mime/SpringFormatNegotiationSpec.groovy b/grails-mimetypes/src/test/groovy/org/grails/web/mime/SpringFormatNegotiationSpec.groovy index 65d4d459575..bd5ed8518f5 100644 --- a/grails-mimetypes/src/test/groovy/org/grails/web/mime/SpringFormatNegotiationSpec.groovy +++ b/grails-mimetypes/src/test/groovy/org/grails/web/mime/SpringFormatNegotiationSpec.groovy @@ -69,6 +69,34 @@ class SpringFormatNegotiationSpec extends Specification { RequestContextHolder.resetRequestAttributes() } + void 'the strategy that resolves the formats of a request is looked up once for it, #how'() { + given: + if (configured) { + start((Settings.MIME_NEGOTIATION_SPRING): true) + } + def first = configured ? request('Accept': 'application/json') : GrailsWebMockUtil.bindMockWebRequest().currentRequest + def strategy = GrailsContentNegotiationStrategy.forRequest(first) + + when: 'the format of the request is read, and the strategy asked for again' + String format = GrailsWebRequest.lookup().currentResponse.format + + then: + format == (configured ? 'json' : 'all') + GrailsContentNegotiationStrategy.forRequest(first).is(strategy) + + when: 'another request is negotiated' + RequestContextHolder.resetRequestAttributes() + def second = configured ? request('Accept': 'application/json') : GrailsWebMockUtil.bindMockWebRequest().currentRequest + + then: "it gets the application's strategy, or, without one, one of its own" + GrailsContentNegotiationStrategy.forRequest(second).is(strategy) == configured + + where: + how | configured + "of the application's MimeTypesConfiguration" | true + 'built for the request in a context without one' | false + } + void "without the setting, Spring MVC's manager is left as it is"() { when: start([:]) From c9608089d2aa7d98ec068105fd061053850212c4 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Thu, 19 Nov 2026 08:56:32 -0800 Subject: [PATCH 20/21] Mark the requests a URL mapping handles only with grails.mime.negotiation.spring UrlMappingsHandlerMapping set BEST_MATCHING_HANDLER_ATTRIBUTE to the mapping it matched, and put an interceptor that takes it off first in every handler chain, and a web unit test set it for the action it calls, whatever the setting said. Only the content negotiation strategies the setting installs read it. The handler mapping now does both only where markHandledRequests is set, which the URL mappings plugin sets from grails.mime.negotiation.spring in the Grails configuration, as the negotiation reads it, and a web unit test sets the attribute only with the setting. Without it, the handler chain and the request attributes are those of 9.0.x. --- .../SpringFormatNegotiationRespondSpec.groovy | 18 +++++ .../testing/web/GrailsWebUnitTest.groovy | 12 ++-- ...appingsBeanDefinitionsPostProcessor.groovy | 15 ++++ .../mapping/UrlMappingsGrailsPlugin.groovy | 7 +- .../UrlMappingsGrailsPluginSpec.groovy | 27 +++++++ .../mvc/UrlMappingsHandlerMapping.groovy | 23 +++++- .../mvc/UrlMappingsHandlerMappingSpec.groovy | 71 +++++++++++++++++-- 7 files changed, 158 insertions(+), 15 deletions(-) diff --git a/grails-test-suite-web/src/test/groovy/grails/rest/web/SpringFormatNegotiationRespondSpec.groovy b/grails-test-suite-web/src/test/groovy/grails/rest/web/SpringFormatNegotiationRespondSpec.groovy index 7e7d0a8c1e7..2dae949093f 100644 --- a/grails-test-suite-web/src/test/groovy/grails/rest/web/SpringFormatNegotiationRespondSpec.groovy +++ b/grails-test-suite-web/src/test/groovy/grails/rest/web/SpringFormatNegotiationRespondSpec.groovy @@ -23,11 +23,13 @@ import org.springframework.http.MediaType import org.springframework.http.ProblemDetail import org.springframework.web.accept.ContentNegotiationManager import org.springframework.web.context.request.ServletWebRequest +import org.springframework.web.servlet.HandlerMapping import grails.artefact.Artefact import grails.config.Settings import grails.testing.web.controllers.ControllerUnitTest import grails.validation.Validateable +import grails.web.mapping.UrlMappingInfo import org.grails.web.mime.GrailsContentNegotiationManager import spock.lang.Specification @@ -49,6 +51,14 @@ class SpringFormatNegotiationRespondSpec extends Specification implements Contro applicationContext.getBean('mvcContentNegotiationManager', ContentNegotiationManager) instanceof GrailsContentNegotiationManager } + void 'the request of the action a web unit test calls is handled by a URL mapping, as the URL mappings mark it in an application'() { + when: + controller + + then: + request.getAttribute(HandlerMapping.BEST_MATCHING_HANDLER_ATTRIBUTE) instanceof UrlMappingInfo + } + void 'what Spring MVC writes for an action of a web unit test is negotiated with the format the request names, as in an application'() { given: request.addHeader('Accept', 'application/json') @@ -231,6 +241,14 @@ class GrailsFormatNegotiationRespondSpec extends Specification implements Contro { config -> config[Settings.WEB_RENDERING_JSON_SPRING] = true } } + void 'the request of the action a web unit test calls is not marked as handled by a URL mapping, as in Grails 9'() { + when: + controller + + then: + request.getAttribute(HandlerMapping.BEST_MATCHING_HANDLER_ATTRIBUTE) == null + } + void "Spring MVC's manager is left as it is"() { expect: applicationContext.getBean('mvcContentNegotiationManager', ContentNegotiationManager).getClass() == ContentNegotiationManager diff --git a/grails-testing-support-web/src/main/groovy/grails/testing/web/GrailsWebUnitTest.groovy b/grails-testing-support-web/src/main/groovy/grails/testing/web/GrailsWebUnitTest.groovy index a66b100fd89..b6b1d8fa797 100644 --- a/grails-testing-support-web/src/main/groovy/grails/testing/web/GrailsWebUnitTest.groovy +++ b/grails-testing-support-web/src/main/groovy/grails/testing/web/GrailsWebUnitTest.groovy @@ -28,6 +28,7 @@ import org.springframework.web.servlet.HandlerMapping import grails.artefact.Controller import grails.artefact.TagLibrary +import grails.config.Settings import grails.core.GrailsClass import grails.core.GrailsControllerClass import grails.core.gsp.GrailsTagLibClass @@ -150,10 +151,13 @@ trait GrailsWebUnitTest implements GrailsUnitTest { webRequest.request.setAttribute(GrailsApplicationAttributes.CONTROLLER, controller) webRequest.controllerName = GrailsNameUtils.getLogicalPropertyName(controller.class.name, ControllerArtefactHandler.TYPE) - // A URL mapping handles the request, as in an application, so that what Spring MVC writes for the action is - // negotiated as there - webRequest.request.setAttribute(HandlerMapping.BEST_MATCHING_HANDLER_ATTRIBUTE, - new ForwardUrlMappingInfo(controllerName: webRequest.controllerName)) + if (grailsApplication.config.getProperty(Settings.MIME_NEGOTIATION_SPRING, Boolean, + Boolean.valueOf(Settings.MIME_NEGOTIATION_SPRING_DEFAULT))) { + // A URL mapping handles the request, as the URL mappings mark it in an application with the setting, so that + // what Spring MVC writes for the action is negotiated as there + webRequest.request.setAttribute(HandlerMapping.BEST_MATCHING_HANDLER_ATTRIBUTE, + new ForwardUrlMappingInfo(controllerName: webRequest.controllerName)) + } controller as T } diff --git a/grails-url-mappings/src/main/groovy/org/grails/plugins/web/mapping/UrlMappingsBeanDefinitionsPostProcessor.groovy b/grails-url-mappings/src/main/groovy/org/grails/plugins/web/mapping/UrlMappingsBeanDefinitionsPostProcessor.groovy index ea7f4621df2..b5df11d4ae9 100644 --- a/grails-url-mappings/src/main/groovy/org/grails/plugins/web/mapping/UrlMappingsBeanDefinitionsPostProcessor.groovy +++ b/grails-url-mappings/src/main/groovy/org/grails/plugins/web/mapping/UrlMappingsBeanDefinitionsPostProcessor.groovy @@ -72,15 +72,27 @@ class UrlMappingsBeanDefinitionsPostProcessor implements BeanDefinitionRegistryP private final boolean reloadEnabled private final boolean corsFilterEnabled private final boolean resolveHiddenHttpMethod + private final boolean markHandledRequests UrlMappingsBeanDefinitionsPostProcessor(boolean reloadEnabled, boolean corsFilterEnabled) { this(reloadEnabled, corsFilterEnabled, false) } UrlMappingsBeanDefinitionsPostProcessor(boolean reloadEnabled, boolean corsFilterEnabled, boolean resolveHiddenHttpMethod) { + this(reloadEnabled, corsFilterEnabled, resolveHiddenHttpMethod, false) + } + + /** + * @param markHandledRequests whether the handler mapping marks the requests its mappings handle for Spring MVC's + * content negotiation, as {@code grails.mime.negotiation.spring} has it + * @since 9.0 + */ + UrlMappingsBeanDefinitionsPostProcessor(boolean reloadEnabled, boolean corsFilterEnabled, boolean resolveHiddenHttpMethod, + boolean markHandledRequests) { this.reloadEnabled = reloadEnabled this.corsFilterEnabled = corsFilterEnabled this.resolveHiddenHttpMethod = resolveHiddenHttpMethod + this.markHandledRequests = markHandledRequests } @Override @@ -95,6 +107,9 @@ class UrlMappingsBeanDefinitionsPostProcessor implements BeanDefinitionRegistryP if (resolveHiddenHttpMethod) { handlerMapping.propertyValues.addPropertyValue('resolveHiddenHttpMethod', true) } + if (markHandledRequests) { + handlerMapping.propertyValues.addPropertyValue('markHandledRequests', true) + } registry.registerBeanDefinition('urlMappingsHandlerMapping', handlerMapping) } diff --git a/grails-url-mappings/src/main/groovy/org/grails/plugins/web/mapping/UrlMappingsGrailsPlugin.groovy b/grails-url-mappings/src/main/groovy/org/grails/plugins/web/mapping/UrlMappingsGrailsPlugin.groovy index 7c374bbbb21..550a34cf3c4 100644 --- a/grails-url-mappings/src/main/groovy/org/grails/plugins/web/mapping/UrlMappingsGrailsPlugin.groovy +++ b/grails-url-mappings/src/main/groovy/org/grails/plugins/web/mapping/UrlMappingsGrailsPlugin.groovy @@ -132,6 +132,10 @@ class UrlMappingsGrailsPlugin extends Plugin { // With no servlet filter rewriting the request method, the handler mapping resolves "_method" // itself so browser forms still reach the PUT, PATCH and DELETE routes of a 'resources' mapping. boolean resolveHiddenHttpMethod = !HiddenHttpMethod.isServletFilterMode(environment) + // Only Spring MVC's content negotiation of grails.mime.negotiation.spring reads which requests a URL + // mapping handles; it is read from the Grails configuration, as the negotiation reads it + boolean markHandledRequests = grailsApplication.config?.getProperty(Settings.MIME_NEGOTIATION_SPRING, Boolean, + Boolean.valueOf(Settings.MIME_NEGOTIATION_SPRING_DEFAULT)) ?: false // The url-mapping holder is a ProxyFactoryBean (reload mode) whose produced UrlMappings // type must stay answerable from the bean definition for by-type autowiring of @@ -140,7 +144,8 @@ class UrlMappingsGrailsPlugin extends Plugin { // FactoryBean.OBJECT_TYPE_ATTRIBUTE. See that class for why the attribute is load-bearing. registry.registerBean('urlMappingsBeanDefinitionsPostProcessor', UrlMappingsBeanDefinitionsPostProcessor) { it.infrastructure().supplier { - new UrlMappingsBeanDefinitionsPostProcessor(reloadEnabled, corsFilterEnabled, resolveHiddenHttpMethod) + new UrlMappingsBeanDefinitionsPostProcessor(reloadEnabled, corsFilterEnabled, resolveHiddenHttpMethod, + markHandledRequests) } } } diff --git a/grails-url-mappings/src/test/groovy/org/grails/plugins/web/mapping/UrlMappingsGrailsPluginSpec.groovy b/grails-url-mappings/src/test/groovy/org/grails/plugins/web/mapping/UrlMappingsGrailsPluginSpec.groovy index 25fd4e32e4e..8ae5d239f59 100644 --- a/grails-url-mappings/src/test/groovy/org/grails/plugins/web/mapping/UrlMappingsGrailsPluginSpec.groovy +++ b/grails-url-mappings/src/test/groovy/org/grails/plugins/web/mapping/UrlMappingsGrailsPluginSpec.groovy @@ -25,9 +25,11 @@ import org.springframework.beans.factory.support.BeanRegistryAdapter import org.springframework.beans.factory.support.DefaultListableBeanFactory import org.springframework.core.env.StandardEnvironment +import grails.config.Settings import grails.core.GrailsApplication import grails.core.GrailsClass import grails.web.mapping.UrlMappings +import org.grails.config.PropertySourcesConfig import org.grails.core.artefact.UrlMappingsArtefactHandler import org.grails.spring.beans.factory.HotSwappableTargetSourceFactoryBean import org.grails.web.mapping.UrlMappingsHolderFactoryBean @@ -103,6 +105,31 @@ class UrlMappingsGrailsPluginSpec extends Specification { !registry.containsBeanDefinition('urlMappingsTargetSource') } + void "the handler mapping marks the requests its mappings handle only with grails.mime.negotiation.spring: #setting"() { + given: + def beanFactory = new DefaultListableBeanFactory() + def config = new PropertySourcesConfig(setting == null ? [:] : [(Settings.MIME_NEGOTIATION_SPRING): setting]) + def application = Mock(GrailsApplication) { + getArtefacts(UrlMappingsArtefactHandler.TYPE) >> { [Mock(GrailsClass)] as GrailsClass[] } + getConfig() >> config + } + applyRegistrar(beanFactory, application) + def registry = new DefaultListableBeanFactory() + + when: + beanFactory.getBean('urlMappingsBeanDefinitionsPostProcessor', UrlMappingsBeanDefinitionsPostProcessor) + .postProcessBeanDefinitionRegistry(registry) + + then: + registry.getBeanDefinition('urlMappingsHandlerMapping').propertyValues.getPropertyValue('markHandledRequests')?.value == marks + + where: + setting || marks + null || null + false || null + true || true + } + private static void applyRegistrar(DefaultListableBeanFactory beanFactory, GrailsApplication application) { def plugin = new UrlMappingsGrailsPlugin(grailsApplication: application) def registrar = plugin.beanRegistrar() diff --git a/grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMapping.groovy b/grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMapping.groovy index 617b7983e96..b6f7b61aae6 100644 --- a/grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMapping.groovy +++ b/grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMapping.groovy @@ -83,6 +83,17 @@ class UrlMappingsHandlerMapping extends AbstractHandlerMapping { */ boolean resolveHiddenHttpMethod = false + /** + * Whether the mapping that handles a request is set as its + * {@link org.springframework.web.servlet.HandlerMapping#BEST_MATCHING_HANDLER_ATTRIBUTE} until the dispatch + * completes, so that what Spring MVC negotiates for the request can tell that a URL mapping handles it. Set with + * {@code grails.mime.negotiation.spring}, whose strategies are all that read it; without it, the request and the + * handler chain are left as Spring MVC's handler mapping leaves them. + * + * @since 9.0 + */ + boolean markHandledRequests = false + protected UrlMappingsHolder urlMappingsHolder // Deliberately not UrlPathHelper.defaultInstance: that instance is read-only, and this field is // protected, so a subclass configuring it (alwaysUseFullPath and friends) must keep working. @@ -165,8 +176,10 @@ class UrlMappingsHandlerMapping extends AbstractHandlerMapping { // before(), so that a failure in one is reported under the route that failed chain.addInterceptor(webRequestInterceptorCount, OBSERVATION_ROUTE_HANDLER) chain.addInterceptor(ERROR_HANDLING_HANDLER) - // First, so that it completes last, whichever interceptor stops the request - chain.addInterceptor(0, HANDLED_REQUEST_HANDLER) + if (markHandledRequests) { + // First, so that it completes last, whichever interceptor stops the request + chain.addInterceptor(0, HANDLED_REQUEST_HANDLER) + } return chain } @@ -185,11 +198,15 @@ class UrlMappingsHandlerMapping extends AbstractHandlerMapping { * The mapping that handles the request, which is also the request's * {@link org.springframework.web.servlet.HandlerMapping#BEST_MATCHING_HANDLER_ATTRIBUTE}, as each of Spring MVC's * handler mappings sets it for the handler it finds, until the dispatch completes, so that what Spring MVC - * negotiates for the request while a URL mapping handles it can tell that one does. + * negotiates for the request while a URL mapping handles it can tell that one does, where + * {@link #markHandledRequests} says so. */ @Override protected Object getHandlerInternal(HttpServletRequest request) throws Exception { Object handler = matchHandler(request) + if (!markHandledRequests) { + return handler + } if (handler != null) { request.setAttribute(BEST_MATCHING_HANDLER_ATTRIBUTE, handler) } diff --git a/grails-web-url-mappings/src/test/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMappingSpec.groovy b/grails-web-url-mappings/src/test/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMappingSpec.groovy index 85cbaeb2826..7f7590cefc9 100644 --- a/grails-web-url-mappings/src/test/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMappingSpec.groovy +++ b/grails-web-url-mappings/src/test/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMappingSpec.groovy @@ -31,6 +31,7 @@ import grails.util.GrailsWebMockUtil import grails.web.Action import grails.web.HyphenatedUrlConverter import grails.web.mapping.AbstractUrlMappingsSpec +import grails.web.mapping.UrlMappingInfo import grails.web.mime.MimeTypeResolver import org.grails.web.errors.GrailsWrappedRuntimeException import org.grails.web.mapping.DefaultUrlMappingData @@ -356,7 +357,7 @@ class UrlMappingsHandlerMappingSpec extends AbstractUrlMappingsSpec { result.view.getUrl() == "/index.html" } - void "the handler chain completes the handled request last, keeps WebRequestInterceptors first, then the route, and appends the error handling last"() { + void "the handler chain keeps WebRequestInterceptors first, then the route, and appends the error handling last"() { given: "a handler mapping with both a WebRequestInterceptor and an ordinary HandlerInterceptor" def handlerMapping = handlerMapping() def plainInterceptor = new HandlerInterceptor() {} @@ -374,22 +375,45 @@ class UrlMappingsHandlerMappingSpec extends AbstractUrlMappingsSpec { webRequest.request.setRequestURI("/foo/bar") def interceptors = handlerMapping.getHandler(webRequest.request).interceptorList - then: "the handled request is completed by the first interceptor, which completes last whichever stops the request" - interceptors[0].class.simpleName == 'HandledRequestHandler' - - and: "the WebRequestInterceptor is adapted and ordered next, ahead of ordinary interceptors" - interceptors[1] instanceof WebRequestHandlerInterceptorAdapter + then: "the WebRequestInterceptor is adapted and ordered first, ahead of ordinary interceptors" + interceptors[0] instanceof WebRequestHandlerInterceptorAdapter interceptors.contains(plainInterceptor) and: "the route is set ahead of the ordinary interceptors, which can fail, and the error handling is last" + interceptors[1].class.simpleName == 'ObservationRouteHandler' + interceptors.indexOf(plainInterceptor) > 1 + interceptors[-1].class.simpleName == 'ErrorHandlingHandler' + !interceptors.any { it.class.simpleName == 'HandledRequestHandler' } + } + + void "where the handler mapping marks the requests it handles, the handled request is completed first in the chain, ahead of the WebRequestInterceptors"() { + given: + def handlerMapping = handlerMapping() + handlerMapping.markHandledRequests = true + def webRequestInterceptor = new WebRequestInterceptor() { + void preHandle(WebRequest request) {} + void postHandle(WebRequest request, ModelMap model) {} + void afterCompletion(WebRequest request, Exception ex) {} + } + handlerMapping.setWebRequestInterceptors([webRequestInterceptor] as WebRequestInterceptor[]) + handlerMapping.setApplicationContext(new StaticWebApplicationContext()) + + when: + def webRequest = GrailsWebMockUtil.bindMockWebRequest() + webRequest.request.setRequestURI("/foo/bar") + def interceptors = handlerMapping.getHandler(webRequest.request).interceptorList + + then: "the first interceptor completes last, whichever interceptor stops the request" + interceptors[0].class.simpleName == 'HandledRequestHandler' + interceptors[1] instanceof WebRequestHandlerInterceptorAdapter interceptors[2].class.simpleName == 'ObservationRouteHandler' - interceptors.indexOf(plainInterceptor) > 2 interceptors[-1].class.simpleName == 'ErrorHandlingHandler' } void "the Grails interceptors are shared rather than allocated per request"() { given: def handlerMapping = handlerMapping() + handlerMapping.markHandledRequests = true handlerMapping.setApplicationContext(new StaticWebApplicationContext()) when: "two separate requests are handled" @@ -655,6 +679,34 @@ class UrlMappingsHandlerMappingSpec extends AbstractUrlMappingsSpec { context.pathPattern == '/foo/bar' } + void 'by default, the mapping that handles a request is not set as its best matching handler, as before Grails 9'() { + given: + def grailsApplication = new DefaultGrailsApplication(FooController) + grailsApplication.initialise() + def handler = new UrlMappingsHandlerMapping(new GrailsControllerUrlMappings(grailsApplication, getUrlMappingsHolder { + '/foo/bar'(controller: 'foo', action: 'bar') + })) + def webRequest = GrailsWebMockUtil.bindMockWebRequest() + def request = webRequest.request + request.requestURI = '/foo/bar' + + when: + def chain = handler.getHandler(request) + + then: + chain.handler instanceof UrlMappingInfo + request.getAttribute(HandlerMapping.BEST_MATCHING_HANDLER_ATTRIBUTE) == null + + when: 'another handler mapping set it, and the URL mappings match nothing for the next dispatch' + def earlier = new ForwardUrlMappingInfo(controllerName: 'foo') + request.setAttribute(HandlerMapping.BEST_MATCHING_HANDLER_ATTRIBUTE, earlier) + request.requestURI = '/spring/endpoint' + + then: 'it is left as it is' + handler.getHandler(request) == null + request.getAttribute(HandlerMapping.BEST_MATCHING_HANDLER_ATTRIBUTE).is(earlier) + } + void 'the mapping that handles a request is its best matching handler, as a Spring MVC handler mapping sets it'() { given: def grailsApplication = new DefaultGrailsApplication(FooController) @@ -663,6 +715,7 @@ class UrlMappingsHandlerMappingSpec extends AbstractUrlMappingsSpec { '/foo/bar'(controller: 'foo', action: 'bar') '/'(view: '/index') })) + handler.markHandledRequests = true def request = GrailsWebMockUtil.bindMockWebRequest().request when: 'a request a controller mapping matches' @@ -690,6 +743,7 @@ class UrlMappingsHandlerMappingSpec extends AbstractUrlMappingsSpec { def handler = new UrlMappingsHandlerMapping(new GrailsControllerUrlMappings(grailsApplication, getUrlMappingsHolder { '/foo/bar'(controller: 'foo', action: 'bar') })) + handler.markHandledRequests = true boolean proceeds = proceed handler.setHandlerInterceptors([new HandlerInterceptor() { @Override @@ -724,6 +778,7 @@ class UrlMappingsHandlerMappingSpec extends AbstractUrlMappingsSpec { def handler = new UrlMappingsHandlerMapping(new GrailsControllerUrlMappings(grailsApplication, getUrlMappingsHolder { '/foo/bar'(controller: 'foo', action: 'bar') })) + handler.markHandledRequests = true def webRequest = GrailsWebMockUtil.bindMockWebRequest() def request = webRequest.request request.requestURI = '/foo/bar' @@ -745,6 +800,7 @@ class UrlMappingsHandlerMappingSpec extends AbstractUrlMappingsSpec { def handler = new UrlMappingsHandlerMapping(new GrailsControllerUrlMappings(grailsApplication, getUrlMappingsHolder { '/foo/bar'(controller: 'foo', action: 'bar') })) + handler.markHandledRequests = true def request = GrailsWebMockUtil.bindMockWebRequest().request request.requestURI = '/foo/bar' handler.getHandler(request) @@ -763,6 +819,7 @@ class UrlMappingsHandlerMappingSpec extends AbstractUrlMappingsSpec { def handler = new UrlMappingsHandlerMapping(getUrlMappingsHolder { '/foo/bar'(controller: 'foo', action: 'bar') }) + handler.markHandledRequests = true def request = GrailsWebMockUtil.bindMockWebRequest().request def springHandler = new Object() request.setAttribute(HandlerMapping.BEST_MATCHING_HANDLER_ATTRIBUTE, springHandler) From 5065b39331655a2f37c4cf19c1b9dd36f77e4f6b Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Thu, 19 Nov 2026 16:24:46 -0800 Subject: [PATCH 21/21] Link What's New to the content negotiation upgrade notes by anchor What's New still named section 26 for the upgrade notes of grails.mime.negotiation.spring, which 9.0.x has renumbered twice since; they are now section 31. It links them by their anchor, upgradingSpringFormatNegotiation, so a renumbering cannot leave the reference stale again. The other sections the sentence lists moved by two when 9.0.x added the Spring Boot 4.2 and graphql-java 26 notes as sections 2 and 3, so they are now 6 to 13 and 15 to 18. --- grails-doc/src/en/guide/introduction/whatsNew.adoc | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/grails-doc/src/en/guide/introduction/whatsNew.adoc b/grails-doc/src/en/guide/introduction/whatsNew.adoc index 9de63e5dc98..592aec42553 100644 --- a/grails-doc/src/en/guide/introduction/whatsNew.adoc +++ b/grails-doc/src/en/guide/introduction/whatsNew.adoc @@ -173,7 +173,8 @@ With `grails.mime.negotiation.spring: true`, which Grails 10 makes the default, `grails.mime` settings of the `Accept` header decide what Spring MVC writes for an action too, such as a `ResponseEntity` it returns. See <>. -See xref:upgrading#upgrading90x[Upgrading from Grails 8 to Grails 9], sections 4 to 11, 13 to 16 and 26. +See xref:upgrading#upgrading90x[Upgrading from Grails 8 to Grails 9], sections 6 to 13 and 15 to 18, and +<>. ==== Hibernate 7 Criteria Queries Can Be Extended