In SpringBoot applications, filters (Filters) are important components for handling HTTP requests and responses. They can intercept before the request reaches the controller or before the response returns to the client.
SpringBoot comes with many practical filters, such as character encoding, cross-domain requests, cache control, etc.
1. CharacterEncodingFilter - Character Encoding Filter
CharacterEncodingFilter
It is one of the most commonly used filters in SpringBoot, which ensures that HTTP requests and responses are encoded correctly and avoids garbled issues.
Functions and configuration
In SpringBoot apps, this filter is enabled by default and uses UTF-8 encoding. You can customize the configuration through the following properties:
# =UTF-8 =true =true
Manual configuration example
@Bean public FilterRegistrationBean<CharacterEncodingFilter> characterEncodingFilter() { CharacterEncodingFilter filter = new CharacterEncodingFilter(); ("UTF-8"); (true); FilterRegistrationBean<CharacterEncodingFilter> registrationBean = new FilterRegistrationBean<>(); (filter); ("/*"); (Ordered.HIGHEST_PRECEDENCE); return registrationBean; }
Practical application: When your application needs to process multilingual content, especially non-ASCII characters including Chinese, Japanese, Arabic, etc., this filter can ensure that the data will not appear garbled during transmission.
2. HiddenHttpMethodFilter - HTTP method conversion filter
HTML forms only support GET and POST methods, but RESTful API usually requires HTTP methods such as PUT and DELETE.HiddenHttpMethodFilter
Simulate these HTTP methods by identifying hidden fields in the form.
Configuration method
# The default is on, if you want to disable it, you can set it to false=true
Example of usage
<form action="/users/123" method="post"> <input type="hidden" name="_method" value="DELETE"/> <button type="submit">Delete users</button> </form>
After the above form is submitted, the filter will convert the POST request to a DELETE request and route it to the corresponding deletion processing method.
@DeleteMapping("/users/{id}") public String deleteUser(@PathVariable Long id) { (id); return "redirect:/users"; }
Practical application: This filter is very useful when you build traditional web applications that do not use JavaScript and want to follow RESTful design principles.
3. FormContentFilter - Form Content Filter
FormContentFilter
Allows processing of form data in non-POST requests (such as PUT, PATCH, etc.) so that the form data of these requests can be parsed like POST requests.
Configuration method
=true
Practical application scenarios
When the client needs to update the resource through PUT request and submit the data in form, this filter ensures that SpringMVC correctly parses the requested data.
@PutMapping("/users/{id}") public String updateUser(@PathVariable Long id, UserForm form) { // Without FormContentFilter, the properties of the form object will not be filled correctly (id, form); return "redirect:/users"; }
4. RequestContextFilter - Request context filter
RequestContextFilter
Create and maintain a RequestContext object to make it available throughout the request processing process, allowing easy access to request-specific information.
Main functions
• Make Locale parsing and topic parsing available for the entire request
• Allows access to the current requested information anywhere
• Support request scoped data binding
Example of usage
@Component public class RequestInfoService { public String getClientInfo() { ServletRequestAttributes attributes = (ServletRequestAttributes) (); HttpServletRequest request = (); return ("Client IP: %s, User-Agent: %s", (), ("User-Agent")); } }
Practical application: The functionality provided by this filter is very useful when you need to access the current HTTP request information in non-Controller components such as the Service layer.
5. CorsFilter - Cross-domain resource sharing filter
CorsFilter
Cross-domain resource sharing (CORS) specification is implemented, allowing browsers to send requests to servers in different domains to resolve the limitations of same-origin policies.
Configuration method
@Bean public CorsFilter corsFilter() { CorsConfiguration config = new CorsConfiguration(); (true); (""); ("*"); ("*"); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); ("/api/**", config); return new CorsFilter(source); }
It can also be configured through properties:
-origins= -methods=GET,POST,PUT,DELETE -headers=Authorization,Content-Type -credentials=true
Practical application: When your front-end application and API are deployed under different domain names, such as the front-end and API, CORS filter is essential.
6. ShallowEtagHeaderFilter - ETag cache filter
ShallowEtagHeaderFilter
Automatically add ETag header information to HTTP responses, helping clients implement efficient caching policies and reduce unnecessary network transmissions.
Principles and configuration
This filter generates an ETag by calculating the hash value of the response content. When the client requests the same resource again, it can determine whether to return a 304 (Not Modified) status code by comparing the ETag.
@Bean public FilterRegistrationBean<ShallowEtagHeaderFilter> shallowEtagHeaderFilter() { FilterRegistrationBean<ShallowEtagHeaderFilter> registration = new FilterRegistrationBean<>(); (new ShallowEtagHeaderFilter()); ("/api/*"); ("shallowEtagHeaderFilter"); return registration; }
Use effect
- First request: Server returns full content and ETag
- Subsequent request: The client sends If-None-Match header, and the server compares the ETag value
- Content not changed: Returns the 304 status code, no response body
- Content has changed: Return 200 status code and new content
Practical application: This filter significantly reduces bandwidth usage and improves response speed when your application provides a lot of static content or infrequently changing API responses.
7. ForwardedHeaderFilter - Forwarded Header Information Filter
When using a load balancer or reverse proxy,ForwardedHeaderFilter
Can process forwarded header information to ensure that the application can correctly identify the client's original information.
Processed header information
• X-Forwarded-Host
• X-Forwarded-Port
• X-Forwarded-Proto
• X-Forwarded-Prefix
• X-Forwarded-For
Configuration example
@Bean public FilterRegistrationBean<ForwardedHeaderFilter> forwardedHeaderFilter() { FilterRegistrationBean<ForwardedHeaderFilter> registration = new FilterRegistrationBean<>(); (new ForwardedHeaderFilter()); (Ordered.HIGHEST_PRECEDENCE); return registration; }
Practical application: When your SpringBoot application is deployed behind a reverse proxy such as Nginx or AWS ELB, this filter ensures that the generated URL and redirects use the correct protocol, hostname, and port.
8. OrderedRequestContextFilter - Ordered Request Context Filter
OrderedRequestContextFilter
yesRequestContextFilter
The extended version ofOrdered
Interfaces allow more precise control of the order of execution in the filter chain.
Differences from RequestContextFilter
• Implemented Ordered interface
• The default priority isFilterRegistrationBean.REQUEST_WRAPPER_FILTER_MAX_ORDER - 10000
• Replace the normal RequestContextFilter in SpringBoot application
Use scenarios
When you have multiple filters and there are dependencies between them,OrderedRequestContextFilter
Ensures that request context initialization is performed at the correct time.
9. ResourceUrlEncodingFilter - Resource URL encoding filter
ResourceUrlEncodingFilter
Mainly used to deal with versioned URLs for static resources, especially when using resource fingerprints or versioning policies.
Functional introduction
• Convert resource paths to URLs containing version information
• Supports content hashing or fixed version number
• Work in conjunction with ResourceUrlProvider
Example of usage
@Configuration public class WebConfig implements WebMvcConfigurer { @Bean public ResourceUrlEncodingFilter resourceUrlEncodingFilter() { return new ResourceUrlEncodingFilter(); } @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { ("/resources/**") .addResourceLocations("classpath:/static/") .setCachePeriod(3600) .resourceChain(true) .addResolver(new VersionResourceResolver() .addContentVersionStrategy("/**")); } }
Use in templates:
<!-- Thymeleaf --> <link rel="stylesheet" th:href="@{/resources/css/}" rel="external nofollow" /> <!-- It may become --> <link rel="stylesheet" href="/resources/css/" rel="external nofollow" />
Practical application: This filter is useful when you need to implement efficient front-end resource caching strategies, especially when deploying new versions to ensure that users get the latest resources without being affected by browser cache.
Summarize
In actual projects, selecting the appropriate filters according to application needs and correctly configuring their execution order will greatly improve the quality and development efficiency of the application.
This is the end of this article about the detailed explanation of the use of 9 SpringBoot's own practical filters. For more related SpringBoot filter content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!