Merge branch '6.1.x'

This commit is contained in:
Sam Brannen
2024-06-25 16:58:45 +02:00
18 changed files with 692 additions and 290 deletions

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -20,8 +20,9 @@ import freemarker.template.Configuration;
/**
* Interface to be implemented by objects that configure and manage a
* FreeMarker Configuration object in a web environment. Detected and
* used by {@link FreeMarkerView}.
* FreeMarker {@link Configuration} object in a web environment.
*
* <p>Detected and used by {@link FreeMarkerView}.
*
* @author Rossen Stoyanchev
* @since 5.0
@@ -29,11 +30,11 @@ import freemarker.template.Configuration;
public interface FreeMarkerConfig {
/**
* Return the FreeMarker Configuration object for the current
* Return the FreeMarker {@link Configuration} object for the current
* web application context.
* <p>A FreeMarker Configuration object may be used to set FreeMarker
* <p>A FreeMarker {@code Configuration} object may be used to set FreeMarker
* properties and shared objects, and allows to retrieve templates.
* @return the FreeMarker Configuration
* @return the FreeMarker {@code Configuration}
*/
Configuration getConfiguration();

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2018 the original author or authors.
* Copyright 2002-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -31,9 +31,10 @@ import org.springframework.ui.freemarker.FreeMarkerConfigurationFactory;
import org.springframework.util.Assert;
/**
* Configures FreeMarker for web usage via the "configLocation" and/or
* "freemarkerSettings" and/or "templateLoaderPath" properties.
* The simplest way to use this class is to specify just a "templateLoaderPath"
* Configures FreeMarker for web usage via the "configLocation",
* "freemarkerSettings", or "templateLoaderPath" properties.
*
* <p>The simplest way to use this class is to specify just a "templateLoaderPath"
* (e.g. "classpath:templates"); you do not need any further configuration then.
*
* <p>This bean must be included in the application context of any application
@@ -42,9 +43,9 @@ import org.springframework.util.Assert;
* by {@code FreeMarkerView}. Implements {@link FreeMarkerConfig} to be found by
* {@code FreeMarkerView} without depending on the bean name of the configurer.
*
* <p>Note that you can also refer to a pre-configured FreeMarker Configuration
* <p>Note that you can also refer to a pre-configured FreeMarker {@code Configuration}
* instance via the "configuration" property. This allows to share a FreeMarker
* Configuration for web and email usage for example.
* {@code Configuration} for web and email usage for example.
*
* <p>This configurer registers a template loader for this package, allowing to
* reference the "spring.ftl" macro library contained in this package:
@@ -54,7 +55,7 @@ import org.springframework.util.Assert;
* &lt;@spring.bind "person.age"/&gt;
* age is ${spring.status.value}</pre>
*
* Note: Spring's FreeMarker support requires FreeMarker 2.3 or higher.
* <p>Note: Spring's FreeMarker support requires FreeMarker 2.3.21 or higher.
*
* @author Rossen Stoyanchev
* @since 5.0
@@ -72,10 +73,10 @@ public class FreeMarkerConfigurer extends FreeMarkerConfigurationFactory
/**
* Set a pre-configured Configuration to use for the FreeMarker web config,
* e.g. a shared one for web and email usage. If this is not set,
* FreeMarkerConfigurationFactory's properties (inherited by this class)
* have to be specified.
* Set a preconfigured {@link Configuration} to use for the FreeMarker web
* config &mdash; for example, a shared one for web and email usage.
* <p>If this is not set, FreeMarkerConfigurationFactory's properties (inherited
* by this class) have to be specified.
*/
public void setConfiguration(Configuration configuration) {
this.configuration = configuration;
@@ -83,9 +84,10 @@ public class FreeMarkerConfigurer extends FreeMarkerConfigurationFactory
/**
* Initialize FreeMarkerConfigurationFactory's Configuration
* if not overridden by a pre-configured FreeMarker Configuration.
* <p>Sets up a ClassTemplateLoader to use for loading Spring macros.
* Initialize FreeMarkerConfigurationFactory's {@link Configuration}
* if not overridden by a pre-configured FreeMarker {@link Configuration}.
* <p>Indirectly sets up a {@link ClassTemplateLoader} to use for loading
* Spring macros.
* @see #createConfiguration
* @see #setConfiguration
*/
@@ -97,7 +99,7 @@ public class FreeMarkerConfigurer extends FreeMarkerConfigurationFactory
}
/**
* This implementation registers an additional ClassTemplateLoader
* This implementation registers an additional {@link ClassTemplateLoader}
* for the Spring-provided macros, added to the end of the list.
*/
@Override
@@ -107,7 +109,7 @@ public class FreeMarkerConfigurer extends FreeMarkerConfigurationFactory
/**
* Return the Configuration object wrapped by this bean.
* Return the {@link Configuration} object wrapped by this bean.
*/
@Override
public Configuration getConfiguration() {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -56,16 +56,40 @@ import org.springframework.web.server.ServerWebExchange;
/**
* A {@code View} implementation that uses the FreeMarker template engine.
*
* <p>Exposes the following configuration properties:
* <ul>
* <li><b>{@link #setUrl(String) url}</b>: the location of the FreeMarker template
* relative to the FreeMarkerConfigurer's
* {@link FreeMarkerConfigurer#setTemplateLoaderPath templateLoaderPath}.</li>
* <li><b>{@link #setEncoding(String) encoding}</b>: the encoding used to decode
* byte sequences to character sequences when reading the FreeMarker template file.
* Default is determined by the FreeMarker {@link Configuration}.</li>
* </ul>
*
* <p>Depends on a single {@link FreeMarkerConfig} object such as
* {@link FreeMarkerConfigurer} being accessible in the application context.
* Alternatively the FreeMarker {@link Configuration} can be set directly on this
* class via {@link #setConfiguration}.
* Alternatively the FreeMarker {@link Configuration} can be set directly via
* {@link #setConfiguration}.
*
* <p>The {@link #setUrl(String) url} property is the location of the FreeMarker
* template relative to the FreeMarkerConfigurer's
* {@link FreeMarkerConfigurer#setTemplateLoaderPath templateLoaderPath}.
* <p><b>Note:</b> To ensure that the correct encoding is used when rendering the
* response as well as when the client reads the response, the following steps
* must be taken.
* <ul>
* <li>Either set the {@linkplain Configuration#setDefaultEncoding(String)
* default encoding} in the FreeMarker {@code Configuration} or set the
* {@linkplain #setEncoding(String) encoding} for this view.</li>
* <li>Configure the supported media type with a {@code charset} equal to the
* configured {@code encoding} via {@link #setSupportedMediaTypes(java.util.List)}
* or {@link FreeMarkerViewResolver#setSupportedMediaTypes(java.util.List)}.</li>
* </ul>
*
* <p>Note: Spring's FreeMarker support requires FreeMarker 2.3 or higher.
* Note, however, that {@link FreeMarkerConfigurer} sets the default encoding in
* the FreeMarker {@code Configuration} to "UTF-8" and that
* {@link org.springframework.web.reactive.result.view.AbstractView AbstractView}
* sets the supported media type to {@code "text/html;charset=UTF-8"} by default.
* Thus, those default values are likely suitable for most applications.
*
* <p>Note: Spring's FreeMarker support requires FreeMarker 2.3.21 or higher.
*
* @author Rossen Stoyanchev
* @author Sam Brannen
@@ -124,18 +148,37 @@ public class FreeMarkerView extends AbstractUrlBasedView {
}
/**
* Set the encoding of the FreeMarker template file.
* <p>By default {@link FreeMarkerConfigurer} sets the default encoding in
* the FreeMarker configuration to "UTF-8". It's recommended to specify the
* encoding in the FreeMarker {@link Configuration} rather than per template
* if all your templates share a common encoding.
* Set the encoding used to decode byte sequences to character sequences when
* reading the FreeMarker template file for this view.
* <p>Defaults to {@code null} to signal that the FreeMarker
* {@link Configuration} should be used to determine the encoding.
* <p>A non-null encoding will override the default encoding determined by
* the FreeMarker {@code Configuration}.
* <p>If the encoding is not explicitly set here or in the FreeMarker
* {@code Configuration}, FreeMarker will read template files using the platform
* file encoding (defined by the JVM system property {@code file.encoding})
* or {@code "utf-8"} if the platform file encoding is undefined. Note,
* however, that {@link FreeMarkerConfigurer} sets the default encoding in the
* FreeMarker {@code Configuration} to "UTF-8".
* <p>It's recommended to specify the encoding in the FreeMarker {@code Configuration}
* rather than per template if all your templates share a common encoding.
* <p>Note that the specified or default encoding is not used for template
* rendering. Instead, an explicit encoding must be specified for the rendering
* process. See the note in the {@linkplain FreeMarkerView class-level
* documentation} for details.
* @see freemarker.template.Configuration#setDefaultEncoding
* @see #getEncoding()
*/
public void setEncoding(@Nullable String encoding) {
this.encoding = encoding;
}
/**
* Get the encoding for the FreeMarker template.
* Get the encoding used to decode byte sequences to character sequences
* when reading the FreeMarker template file for this view, or {@code null}
* to signal that the FreeMarker {@link Configuration} should be used to
* determine the encoding.
* @see #setEncoding(String)
*/
@Nullable
protected String getEncoding() {

View File

@@ -0,0 +1,207 @@
/*
* Copyright 2002-2024 the original author or authors.
*
* Licensed 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.springframework.web.reactive.config;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import freemarker.cache.ClassTemplateLoader;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import reactor.test.StepVerifier;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.reactive.DispatcherHandler;
import org.springframework.web.reactive.result.view.freemarker.FreeMarkerConfigurer;
import org.springframework.web.reactive.result.view.freemarker.FreeMarkerViewResolver;
import org.springframework.web.testfixture.http.server.reactive.MockServerHttpRequest;
import org.springframework.web.testfixture.http.server.reactive.MockServerHttpResponse;
import org.springframework.web.testfixture.server.MockServerWebExchange;
import static java.nio.charset.StandardCharsets.ISO_8859_1;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatRuntimeException;
/**
* Integration tests for view resolution with {@code @EnableWebFlux}.
*
* @author Sam Brannen
* @since 6.1.11
* @see org.springframework.web.servlet.config.annotation.ViewResolutionIntegrationTests
*/
class WebFluxViewResolutionIntegrationTests {
private static final MediaType TEXT_HTML_UTF8 = MediaType.parseMediaType("text/html;charset=UTF-8");
private static final MediaType TEXT_HTML_ISO_8859_1 = MediaType.parseMediaType("text/html;charset=ISO-8859-1");
private static final String EXPECTED_BODY = "<html><body>Hello, Java Café</body></html>";
@Nested
class FreeMarkerTests {
private static final ClassTemplateLoader classTemplateLoader =
new ClassTemplateLoader(WebFluxViewResolutionIntegrationTests.class, "");
@Test
void freemarkerWithInvalidConfig() {
assertThatRuntimeException()
.isThrownBy(() -> runTest(InvalidFreeMarkerWebFluxConfig.class))
.withMessageContaining("In addition to a FreeMarker view resolver ");
}
@Test
void freemarkerWithDefaults() throws Exception {
MockServerHttpResponse response = runTest(FreeMarkerWebFluxConfig.class);
StepVerifier.create(response.getBodyAsString()).expectNext(EXPECTED_BODY).expectComplete().verify();
assertThat(response.getHeaders().getContentType()).isEqualTo(TEXT_HTML_UTF8);
}
@Test
void freemarkerWithExplicitDefaultEncoding() throws Exception {
MockServerHttpResponse response = runTest(ExplicitDefaultEncodingConfig.class);
StepVerifier.create(response.getBodyAsString()).expectNext(EXPECTED_BODY).expectComplete().verify();
assertThat(response.getHeaders().getContentType()).isEqualTo(TEXT_HTML_UTF8);
}
@Test
void freemarkerWithExplicitDefaultEncodingAndContentType() throws Exception {
MockServerHttpResponse response = runTest(ExplicitDefaultEncodingAndContentTypeConfig.class);
StepVerifier.create(response.getBodyAsString()).expectNext(EXPECTED_BODY).expectComplete().verify();
// When the Content-Type (supported media type) is explicitly set on the view resolver, it should be used.
assertThat(response.getHeaders().getContentType()).isEqualTo(TEXT_HTML_ISO_8859_1);
}
@EnableWebFlux
@Configuration(proxyBeanMethods = false)
static class InvalidFreeMarkerWebFluxConfig implements WebFluxConfigurer {
@Override
public void configureViewResolvers(ViewResolverRegistry registry) {
registry.freeMarker();
}
}
@Configuration(proxyBeanMethods = false)
static class FreeMarkerWebFluxConfig extends AbstractWebFluxConfig {
@Override
public void configureViewResolvers(ViewResolverRegistry registry) {
registry.freeMarker();
}
@Bean
public FreeMarkerConfigurer freeMarkerConfigurer() {
FreeMarkerConfigurer configurer = new FreeMarkerConfigurer();
configurer.setPreTemplateLoaders(classTemplateLoader);
return configurer;
}
}
@Configuration(proxyBeanMethods = false)
static class ExplicitDefaultEncodingConfig extends AbstractWebFluxConfig {
@Override
public void configureViewResolvers(ViewResolverRegistry registry) {
registry.freeMarker();
}
@Bean
public FreeMarkerConfigurer freeMarkerConfigurer() {
FreeMarkerConfigurer configurer = new FreeMarkerConfigurer();
configurer.setPreTemplateLoaders(classTemplateLoader);
configurer.setDefaultEncoding(UTF_8.name());
return configurer;
}
}
@Configuration(proxyBeanMethods = false)
static class ExplicitDefaultEncodingAndContentTypeConfig extends AbstractWebFluxConfig {
@Autowired
ApplicationContext applicationContext;
@Override
public void configureViewResolvers(ViewResolverRegistry registry) {
FreeMarkerViewResolver resolver = new FreeMarkerViewResolver("", ".ftl");
resolver.setSupportedMediaTypes(List.of(TEXT_HTML_ISO_8859_1));
resolver.setApplicationContext(this.applicationContext);
registry.viewResolver(resolver);
}
@Bean
public FreeMarkerConfigurer freeMarkerConfigurer() {
FreeMarkerConfigurer configurer = new FreeMarkerConfigurer();
configurer.setPreTemplateLoaders(classTemplateLoader);
configurer.setDefaultEncoding(ISO_8859_1.name());
return configurer;
}
@Override
@Bean
public SampleController sampleController() {
return new SampleController("index_ISO-8859-1");
}
}
}
private static MockServerHttpResponse runTest(Class<?> configClass) throws Exception {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(configClass);
MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/"));
new DispatcherHandler(context).handle(exchange).block(Duration.ofSeconds(1));
return exchange.getResponse();
}
@EnableWebFlux
abstract static class AbstractWebFluxConfig implements WebFluxConfigurer {
@Bean
public SampleController sampleController() {
return new SampleController("index_UTF-8");
}
}
@Controller
static class SampleController {
private final String viewName;
SampleController(String viewName) {
this.viewName = viewName;
}
@GetMapping("/")
String index(Map<String, Object> model) {
model.put("hello", "Hello");
return this.viewName;
}
}
}

View File

@@ -111,10 +111,11 @@ class RequestMappingViewResolutionIntegrationTests extends AbstractRequestMappin
@Bean
public FreeMarkerConfigurer freeMarkerConfig() {
FreeMarkerConfigurer configurer = new FreeMarkerConfigurer();
configurer.setPreferFileSystemAccess(false);
configurer.setTemplateLoaderPath("classpath*:org/springframework/web/reactive/view/freemarker/");
return configurer;
// No need to configure a custom template loader path via setTemplateLoaderPath(),
// since FreeMarkerConfigurer already registers a
// new ClassTemplateLoader(FreeMarkerConfigurer.class, ""), which automatically
// finds template files in the same package as this test class.
return new FreeMarkerConfigurer();
}
}

View File

@@ -0,0 +1 @@
<html><body>${hello}, Java Caf<61></body></html>

View File

@@ -0,0 +1 @@
<html><body>${hello}, Java Café</body></html>