Prior to this commit, the ResourceUrlEncodingFilter would fail with a
StringIndexOutOfBoundsException when:
* the current request has a servlet context
* the URL to encode is relative and is shorter than the context value
This change defensively checks for those lengths and delegates to the
parent implementation if necessary.
Issue: SPR-13018
Prior to this commit, AntPathMatcher would not correctly combine a path
that ends with a separator with a path that starts with a separator.
For example, `/foo/` + `/bar` combined into `/foo//bar`.
Specifically, this commit:
- Removes the duplicated separator in combined paths
- Improves RequestMappingInfo's toString() representation
- Fixes Javadoc formatting in AntPathMatcher
- Polishes AntPathMatcherTests
- Polishes Javadoc in AbstractRequestCondition
Issue: SPR-12975
Prior to this change, the `UrlTag` would simply append the remote
context and the path value in case of a context relative URL.
The following code snippet would output "//foo":
```
<spring:url value="/foo" context="/" />
```
This change now removes trailing slashes in remote context to avoid
this.
Issue: SPR-12782
- Methods which search for a specific annotation now properly ensure
that the sought annotation was actually found.
- Both the "get" and the "find" search algorithms no longer needlessly
traverse meta-annotation hierarchies twice.
- Both the "get" and the "find" search algorithms now properly
increment the metaDepth when recursively searching within the
meta-annotation hierarchy.
- Redesigned getMetaAnnotationTypes() so that it doesn't needlessly
search irrelevant annotations.
- Documented and tested hasMetaAnnotationTypes().
- Documented isAnnotated().
Issue: SPR-11514
Before this change AbstractHandlerMethodMapping used a map from Method
to CorsConfiguration. That works for regular @RequestMapping methods.
However frameworks like Spring Boot and Spring Integration may
programmatically register the same Method under multiple mappings,
i.e. adapter/gateway type classes.
This change ensures that CorsConfiguraiton is indexed by HandlerMethod
so that we can store CorsConfiguration for different handler instances
even when the method is the same.
In order for to make this work, HandlerMethod now provides an
additional field called resolvedFromHandlerMethod that returns the
original HandlerMethod (with the String bean name). This makes it
possible to perform reliable lookups.
Issue: SPR-11541
This commit introduces failing (but currently disabled) test cases in
HandlerMethodAnnotationDetectionTests that attempt to reproduce the
scenario described in SPR-9517.
See: ParameterizedSubclassDoesNotOverrideConcreteImplementationsFromGenericAbstractSuperclass
Furthermore, this commit also introduces passing tests cases for a
similar scenario. See: ParameterizedSubclassOverridesDefaultMappings
Issue: SPR-9517
CorsConfiguration now provides methods to check and determine the
allowed origin, method, and headers according to its own configuration.
This simplifies significantly the work that needs to be done from
DefaultCorsProcessor. However an alternative CorsProcessor can still
access the raw CorsConfiguration and perform its own checks.
Issue: SPR-12885
This commit adds CORS related headers to HttpHeaders
and update DefaultCorsProcessor implementation to
use ServerHttpRequest and ServerHttpResponse instead
of HttpServletRequest and HttpServletResponse. Usage
of ServerHttpResponse allows to avoid using Servlet 3.0
specific methods in order keep CORS support Servlet 2.5
compliant.
Issue: SPR-12885
The change to provide public register/unregister methods in
AbstractHandlerMethodMapping assumed that a single method cannot be
mapped more than once. This is not the case with the MvcEndpoints and
EndpointHandlerMapping from Spring Boot which wrap one or more
non-web Endpoint types with an MvcEndpointAdapter in order to expose
them for use over the web. In effect Spring MVC sees a single handler
method mapped many times.
This change removes that assumption so rather than unregistering with
a HandlerMethod, which is not necessarily unique, the unregister method
now takes the actual mapping, which is the only thing that should actually
be unique.
Issue: SPR-11541
This commit adds additional context to the exception message generated
when two candidate methods are discovered in MvcUriComponentsBuilder's
getMethod(Class<?>, String, Object...).
Issue: SPR-12977
This commit introduces a new fromMethodNameWithBridgedMethod() test in
MvcUriComponentsBuilderTests which is currently disabled via @Ignore
until this bug is resolved.
Issue: SPR-12977
When used in combination with GzipResourceResolver, the
CachingResourceResolver does not properly cache results, since it only
takes the request path as a input for cache key generation.
Here's an example of that behavior:
1. an HTTP client requests a resource with `Accept-Encoding: gzip`, so
the GzipResourceResolver can resolve a gzipped resource.
2. the configured CachingResourceResolver caches that resource.
3. another HTTP client requests the same resource, but it does not
support gzip encoding; the previously cached gzipped resource is still
returned.
This commit uses the presence/absence of gzip encoding support as an
input in cache keys generation.
Issue: SPR-12982
Before this change AbstractHandlerMethodMapping contained multiple
maps all containing different kinds of mapping meta-data. After the
change a MappingDefinitionRegistry inner class encapsulates these
fields along with their initialization code.
Issue: SPR-11541
Before 4.2 the MvcUriComponentsBuilder exposed only static factory
methods and therefore there should be no reason for it to extend
UriComponentsBuilder (design oversight). It's also highly unlikely
for application code to treat MvcUriCB as UriCB since there is no
need and no way to obtain an instance (constructor is protected).
This change removes the base class declaration from MvcUriCB.
Issue: SPR-12617
Before this change MvcUriComponentsBuilder exposed only static factory
methods for creating links where the links are relative to the current
request or a baseUrl explicitly provided as an argument.
This change allows creating an MvcUriComponents builder instance with
a built-in baseUrl. The instance can then be used with non-static
withXxx(...) method alternatives to the static fromXxx(...) methods.
Issue: SPR-12617
This commit adds support for script based templating. Any templating
library running on top of a JSR-223 ScriptEngine that implements
Invocable like Nashorn or JRuby could be used.
For example, in order to render Mustache templates thanks to the Nashorn
Javascript engine provided with Java 8+, you should declare the following
configuration:
@Configuration
@EnableWebMvc
public class MustacheConfig extends WebMvcConfigurerAdapter {
@Override
public void configureViewResolvers(ViewResolverRegistry registry) {
registry.scriptTemplate();
}
@Bean
public ScriptTemplateConfigurer configurer() {
ScriptTemplateConfigurer configurer = new ScriptTemplateConfigurer();
configurer.setEngineName("nashorn");
configurer.setScripts("mustache.js");
configurer.setRenderObject("Mustache");
configurer.setRenderFunction("render");
return configurer;
}
}
The XML counterpart is:
<beans>
<mvc:annotation-driven />
<mvc:view-resolvers>
<mvc:script-template />
</mvc:view-resolvers>
<mvc:script-template-configurer engine-name="nashorn" render-object="Mustache" render-function="render">
<mvc:script location="mustache.js" />
</mvc:script-template-configurer>
</beans>
Tested with:
- Handlebars running on Nashorn
- Mustache running on Nashorn
- React running on Nashorn
- EJS running on Nashorn
- ERB running on JRuby
- String templates running on Jython
Issue: SPR-12266
AbstractHttpMessageConverter now tries to call getDefaultContentType
with the actual value to be converted to see if that will result in
a more concrete mediat type than application/octet-stream.
Issue: SPR-12894
This commit introduces support for CORS in Spring Framework.
Cross-origin resource sharing (CORS) is a mechanism that allows
many resources (e.g. fonts, JavaScript, etc.) on a web page to
be requested from another domain outside the domain from which
the resource originated. It is defined by the CORS W3C
recommandation (http://www.w3.org/TR/cors/).
A new annotation @CrossOrigin allows to enable CORS support
on Controller type or method level. By default all origins
("*") are allowed.
@RestController
public class SampleController {
@CrossOrigin
@RequestMapping("/foo")
public String foo() {
// ...
}
}
Various @CrossOrigin attributes allow to customize the CORS configuration.
@RestController
public class SampleController {
@CrossOrigin(origin = { "http://site1.com", "http://site2.com" },
allowedHeaders = { "header1", "header2" },
exposedHeaders = { "header1", "header2" },
method = RequestMethod.DELETE,
maxAge = 123, allowCredentials = "true")
@RequestMapping(value = "/foo", method = { RequestMethod.GET, RequestMethod.POST} )
public String foo() {
// ...
}
}
A CorsConfigurationSource interface can be implemented by HTTP request
handlers that want to support CORS by providing a CorsConfiguration
that will be detected at AbstractHandlerMapping level. See for
example ResourceHttpRequestHandler that implements this interface.
Global CORS configuration should be supported through ControllerAdvice
(with type level @CrossOrigin annotated class or class implementing
CorsConfigurationSource), or with XML namespace and JavaConfig
configuration, but this is not implemented yet.
Issue: SPR-9278
This commit adds a filters property to MappingJacksonValue
and also manages a special FilterProvider class name model key in
order to be able to specify a customized FilterProvider for each
handler method execution, and thus provides a more dynamic
alternative to our existing JsonView support.
A filters property is also now available in Jackson2ObjectMapperBuilder
and Jackson2ObjectMapperFactoryBean in order to set easily a
global FilterProvider.
More details about @JsonFilter at
http://wiki.fasterxml.com/JacksonFeatureJsonFilter.
Issue: SPR-12586
The check for an empty request body InputStream is now in the base
class AbstractMessageConverterMethodArgumentResolver shared for
all arguments that involve reading with an HttpMessageConverter --
@RequestBody, @RequestPart, and HttpEntity.
When an empty body is detected any configured RequestBodyAdvice is
given a chance to select a default value or leave it as null.
Issue: SPR-12778, SPR-12860, SPR-12861
RequestBodyAdvice is analogous to ResponseBodyAdvice (added in 4.1)
but for intercepting for reading the request with an
HttpMessageConverter for resolving an @RequestBody or an HttpEntity
method argument.
Issue: SPR-12501
Introduces an AbstractXlsView and dedicated subclasses for POI's xmlx support.
Deprecates the traditional AbstractExcelView which is based on pre POI 3.5 API.
Issue: SPR-6898
Prior to this commit, Cache-Control HTTP headers could be set using
a WebContentInterceptor and configured cache mappings.
This commit adds support for cache-related HTTP headers at the controller
method level, by returning a ResponseEntity instance:
ResponseEntity.status(HttpStatus.OK)
.cacheControl(CacheControl.maxAge(1, TimeUnit.HOURS).cachePublic())
.eTag("deadb33f8badf00d")
.body(entity);
Also, this change now automatically checks the "ETag" and
"Last-Modified" headers in ResponseEntity, in order to respond HTTP
"304 - Not Modified" if necessary.
Issue: SPR-8550
This commit improves HTTP caching defaults and flexibility in
Spring MVC.
1) Better default caching headers
The `WebContentGenerator` abstract class has been updated with
better HTTP defaults for HTTP caching, in line with current
browsers and proxies implementation (wide support of HTTP1.1, etc);
depending on the `setCacheSeconds` value:
* sends "Cache-Control: max-age=xxx" for caching responses and
do not send a "must-revalidate" value by default.
* sends "Cache-Control: no-store" or "Cache-Control: no-cache"
in order to prevent caching
Other methods used to set specific header such as
`setUseExpiresHeader` or `setAlwaysMustRevalidate` are now deprecated
in favor of `setCacheControl` for better flexibility.
Using one of the deprecated methods re-enables previous HTTP caching
behavior.
This change is applied in many Handlers, since
`WebContentGenerator` is extended by `AbstractController`,
`WebContentInterceptor`, `ResourceHttpRequestHandler` and others.
2) New CacheControl builder class
This new class brings more flexibility and allows developers
to set custom HTTP caching headers.
Several strategies are provided:
* `CacheControl.maxAge(int)` for caching responses with a
"Cache-Control: max-age=xxx" header
* `CacheControl.noStore()` prevents responses from being cached
with a "Cache-Control: no-store" header
* `CacheControl.noCache()` forces caches to revalidate the cached
response before reusing it, with a "Cache-Control: no-store" header.
From that point, it is possible to chain method calls to craft a
custom CacheControl instance:
```
CacheControl cc = CacheControl.maxAge(1, TimeUnit.HOURS)
.cachePublic().noTransform();
```
3) Configuring HTTP caching in Resource Handlers
On top of the existing ways of configuring caching mechanisms,
it is now possible to use a custom `CacheControl` to serve
resources:
```
@Configuration
public class MyWebConfig extends WebMvcConfigurerAdapter {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
CacheControl cc = CacheControl.maxAge(1, TimeUnit.HOURS);
registry.addResourceHandler("/resources/**)
.addResourceLocations("classpath:/resources/")
.setCacheControl(cc);
}
}
```
or
```
<mvc:resources mapping="/resources/**" location="classpath:/resources/">
<mvc:cachecontrol max-age="3600" cache-public="true"/>
</mvc:resources>
```
Issue: SPR-2779, SPR-6834, SPR-7129, SPR-9543, SPR-10464
This commit introduces support for HTTP byte ranges in the
ResourceHttpRequestHandler. This support consists of a number of
changes:
- Parsing of HTTP Range headers in HttpHeaders, using a new HttpRange
class and inner ByteRange/SuffixByteRange subclasses.
- MIME boundary generation moved from FormHttpMessageConverter to
MimeTypeUtils.
- writePartialContent() method introduced in ResourceHttpRequestHandler,
handling the byte range logic
- Additional partial content tests added to
ResourceHttpRequestHandlerTests.
Issue: SPR-10805
Revised HandlerMethod.getBeanType() impl for both web and messaging.
In addition, HandlerMethods get created with the internal BeanFactory now.
Issue: SPR-12832
FlashMap now has a single field reflecting the expiration time and
also provides accessors that can be used for serialization purposes.
Issue: SPR-12757
AbstractFlashMapManager no longer decodes the target query parameters
it needs to use to match to the request after the redirect.
Instead it stores query parameters as-is adn then relies on parsing the
encoded query string after the redirect.
Issue: SPR-12569
This commit ensures that @NumberFormat can be used as a
meta-annotation, as was already the case for @DateTimeFormat.
In addition, this commit polishes FormattingConversionServiceTests and
MvcNamespaceTests.
Issue: SPR-12743
Prior to this change, location checks for serving resources would append
`/` to the location path it didn't already have one.
This commit makes sure not to append a `/` if the provided location is
actually a file.
Issue: SPR-12747
Before this change, detection of X-Forwarded-* headers was only built
into ServletUriComponentsBuilder.
This change adds a new method for creating a UriComponentsBuilder from
an existing HttpRequest. This is equivalent to the fromUri method +
X-Forwarded-* header values.
Prior to this change, the `ResourceUrlProvider.getForLookupPath` method
would try to match handlers using the keySet order in the
handlerMappings Map. In case of several matches, the handler used for
the return value could vary, since the registration order in the
handlerMappings can't be guaranteed in the configuration.
This commit now collects all matching handlers and sort them using a
`PatternComparator`, in order to try each handler from the most specific
mapping to the least.
Issue: SPR-12647
This commit adds ResponseBodyEmitter and SseEmitter (and also
ResponseEntity<ResponseBodyEmitter> and ResponseEntity<SseEmitter>) as
new return value types supported on @RequestMapping controller methods.
See Javadoc on respective types for more details.
Issue: SPR-12212
Prior to this change, the ResourceUrlProvider would listen to
ContextRefreshedEvents and autodetect resource handlers each time. This
can cause issues when multiple contexts are involved and the last one
has no resource handler, thus clearing the previously detected ones.
This commit disables resource handlers auto-detection once some have
been detected with a refreshed context.
Issue: SPR-12592
Prior to this change, location paths used for resource handling would
not allow "non-cleaned, relative paths" such as
`file://home/user/static/../static/`. When checking if the resolved
resource's path starts with the location path, a mismatch would happen
when comparing for example:
* the location `file://home/user/static/../static/`
* and the resource `file://home/user/static/resource.txt`
This commit cleans the location path before comparing it to the resource
path.
Issue: SPR-12624
This commit allows the use of "protcol relative URLs" (i.e. URLs without
scheme, starting with `//`), often used to serve resources automatically
from https or http with third party domains.
This syntax is allowed by RFC 3986.
Issue: SPR-12632
This commit fixes the default value for the contextRelative attribute of
a RedirectView, when this view is registered via a
RedirectViewController in XML. The value is set to true.
Note that the default value for this is correctly documented in
spring-mvc-4.1.xsd. Also, the documentation and implementation for its
javadoc counterpart also enforces true as a default value.
Issue: SPR-12607
This commit introduces the SpringHandlerInstantiator
class, a Jackson HandlerInstantiator that allows to autowire
Jackson handlers (JsonSerializer, JsonDeserializer, KeyDeserializer,
TypeResolverBuilder and TypeIdResolver) if needed.
SpringHandlerInstantiator is automatically used with
@EnableWebMvc and <mvc:annotation-driven />.
Issue: SPR-10768
Prior to this change, the ResourceUrlEncodingFilter would work well when
the application is mapped to "/". But when mapped to a non-empty servlet
context, this filter would not properly encode URLs and apply
ResourceResolver URL resolution for resources.
This commit makes sure that the lookup path is properly resolved in the
request URI, taking into account the servlet context.
Issue: SPR-12459
SPR-12354 applied new checks to make sure that served static resources
are under authorized locations.
Prior to this change, serving static resources from Servlet 3 locations
such as "/webjars/" would not work since those locations can be within
one of the JARs on path. In that case, the checkLocation method would
return false and disallow serving that static resource.
This change fixes this issue by making sure to call the
`ServletContextResource.getPath()` method for servlet context resources.
Note that there's a known workaround for this issue, which is using a
classpath scheme as location, such as:
"classpath:/META-INF/resources/webjars/" instead of "/webjars".
Issue: SPR-12432
- remove leading '/' and control chars
- improve url and relative path checks
- account for URL encoding
- add isResourceUnderLocation final verification
Issue: SPR-12354
With SPR-9293, it is now possible to HTML escape text while taking into
account the current response encoding. When using UTF-* encodings, only
XML markup significant characters are escaped, since UTF-* natively
support those characters.
This commit adds a new servlet context parameter to enable this fix by
default in a Spring MVC application:
<context-param>
<param-name>responseEncodedHtmlEscape</param-name>
<param-value>true</param-value>
</context-param>
Issue: SPR-12350, SPR-12132
During the HTTP Content Negotiation phase, the ContentNegotiationManager
uses configured ContentNegotiationStrategy(ies) to define the list of
content types accepted by the client.
When HTTP clients don't send Accept headers, nor use a configured
file extension in the request, nor a request param, developers can
define a default content type using the
ContentNegotiationConfigurer.defaultContentType() method.
This change adds a new overloaded defaultContentType method that takes a
ContentNegotiationStrategy as an argument. This strategy will take the
current request as an argument and return a default content type.
Issue: SPR-12286