[JAVA] Specify the encoding of static resources in Spring Boot

Spring Boot has the ability to host static resources (https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-developing-web-applications.html#boot- There is features-spring-mvc-static-content), but unlike the response from Controller, I was addicted to not giving charset to Content-Type in the response header of the static resource.

Expected response header


Content-Type: text/html;charset=UTF-8

Actual response header


Content-Type: text/html

Confirmation environment

Conclusion

You can specify the encoding for files with a specific extension by implementing WebServerFactoryCustomizer to customize the behavior of the built-in Tomcat container. However, only if the charset is uniquely determined for the extension.

import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.server.MimeMappings;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.stereotype.Component;

@Component
public class ServletCustomizer implements WebServerFactoryCustomizer<TomcatServletWebServerFactory> {

    @Override
    public void customize(TomcatServletWebServerFactory factory) {
        MimeMappings mappings = new MimeMappings(MimeMappings.DEFAULT);
        mappings.add("html", "text/html;charset=UTF-8");
        factory.setMimeMappings(mappings);
    }
}

Bot plan

I will leave a few ideas I tried before I got here.

1. Customize CharacterEncodingFilter

By adjusting the setting of application.properties, the behavior of CharacterEncodingFilter can be changed. You can change it and force the charset to be output.

application.properties


# Charset of HTTP requests and responses. 
spring.http.encoding.charset=UTF-8
# Whether to force the encoding to the configured charset on HTTP responses.
spring.http.encoding.force-response=true

It works as expected for HTML files, but as the name suggests, it is forcibly added to image files, etc., which is a shame.

Content-Type: image/jpeg;charset=UTF-8

2. Extension of CharacterEncodingFilter

CharacterEncodingFilter outputs uniformly, so it seems good to derive this class and implement your own filter.

At first glance it seems to work, but this method is limited to cases where it can be uniquely determined from the request URL.

If you are doing something like returning index.html as a fallback page if the path cannot be resolved (as I did in my case), the request URL will not necessarily include the extension. Not always, so there is not enough information to make the decision.

@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**/*")
            .addResourceLocations("classpath:/static/")
            .resourceChain(true)
            .addResolver(new PathResourceResolver() {
                @Override
                protected Resource getResource(String resourcePath, Resource location) throws IOException {
                    Resource requestedResource = location.createRelative(resourcePath);
                    return requestedResource.exists() && requestedResource.isReadable()
                        ? requestedResource : new ClassPathResource("/static/index.html");
                }
            });
    }
}

Reference information

Recommended Posts

Specify the encoding of static resources in Spring Boot
Specify spring.profiles.active via context-param of web.xml in Spring Boot
Get a proxy instance of the component itself in Spring Boot
Static file access priority in Spring boot
Procedure to make the value of the property file visible in Spring Boot
The story of raising Spring Boot 1.5 series to 2.1 series
Let's check the feel of Spring Boot + Swagger 2.0
View the Gradle task in the Spring Boot project
Organize the differences in behavior of @NotBlank, @NotEmpty, @NotNull with Spring Boot + Thymeleaf
Get the path defined in Controller class of Spring boot as a list
Resource handler settings when delivering SPA with the static resource function of Spring Boot
How to set environment variables in the properties file of Spring boot application
Get multiple Resources that match the pattern in spring
I checked asynchronous execution of queries in Spring Boot 1.5.9
[For beginners] DI ~ The basics of DI and DI in Spring ~
Access the built-in h2db of spring boot with jdbcTemplate
05. I tried to stub the source of Spring Boot
I tried to reduce the capacity of Spring Boot
How to use CommandLineRunner in Spring Batch of Spring Boot
Check the behavior of getOne, findById, and query methods in Spring Boot + Spring Data JPA
Set context-param in Spring Boot
Spring Boot 2 multi-project in Gradle
Major changes in Spring Boot 1.5
NoHttpResponseException in Spring Boot + WireMock
Spring Boot 1.x will reach EOL in the next year.
The story of raising Spring Boot from 1.5 series to 2.1 series part2
About the function of Spring Boot due to different versions
A quick explanation of the five types of static in Java
Put the file in the properties of string in spring xml configuration
Accelerate testing of Validators that require DI in Spring Boot
A story packed with the basics of Spring Boot (solved)
Static resources could not be distributed from WebFlux when @EnableWebFlux was granted in Spring Boot
Branch processing by the return value of RestTemplate and the status code of ResponseEntity in Spring Boot
Spring Boot Hello World in Eclipse
Spring Boot application development in Eclipse
Memorandum of understanding when Spring Boot 1.5.10 → Spring Boot 2.0.0
Spring Boot for the first time
Sample code that uses the Mustache template engine in Spring Boot
Write test code in Spring Boot
Specify the java location in eclipse.ini
See the relative redirect behavior with the server.tomcat.use-relative-redirects setting in Spring Boot
Going out of message (Spring boot)
What I did in the migration from Spring Boot 1.4 series to 2.0 series
Implement REST API in Spring Boot
What is @Autowired in Spring boot?
[Spring Boot] Role of each class
Spring validation was important in the order of Form and BindingResult
Implement Spring Boot application in Gradle
What I did in the migration from Spring Boot 1.5 series to 2.0 series
See the behavior of entity update with Spring Boot + Spring Data JPA
I want to control the default error message of Spring Boot
[Spring Boot] Until @Autowired is run in the test class [JUnit5]
Form that receives the value of the repeating item in Spring MVC
Order of processing in the program
I want to know the Method of the Controller where the Exception was thrown in the ExceptionHandler of Spring Boot
Thymeleaf usage notes in Spring Boot
Filter the result of BindingResult [Spring]
Unknown error in line 1 of pom.xml when using Spring Boot in Eclipse
Coexistence of Flyway in the embedded database (h2) of the development environment and the release database (SQL Server) with Spring Boot
[Spring Boot] List of validation rules that can be used in the property file for error messages
[Spring Boot] I investigated how to implement post-processing of the received request.