我的项目中没有使用web.xml。因此,我为我的MVC配置扩展了WebMvcConfigurerAdapter,为初始化应用程序扩展了AbstractAnnotationConfigDispatcherServletInitializer。我需要将编码设置为UTF-8。如何添加过滤器映射?
我想在基于Java的配置中实现以下代码。
<filter>
<filter-name>characterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
答案 0 :(得分:2)
您可以将bean添加到配置类
中@Bean
public FilterRegistrationBean encodingFilter() {
CharacterEncodingFilter encodingFilter = new CharacterEncodingFilter("UTF-8", true);
FilterRegistrationBean filterRegBean = new FilterRegistrationBean();
filterRegBean.setUrlPatterns(getRootPathUrls());
filterRegBean.setFilter(encodingFilter);
filterRegBean.setOrder(1);
return filterRegBean;
}
private List<String> getRootPathUrls() {
List<String> urlPatterns = new ArrayList<String>();
urlPatterns.add("/*");
return urlPatterns;
}
文档 Here
答案 1 :(得分:1)
我找到了溶剂here。
@Configuration
@EnableWebMvcSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
CharacterEncodingFilter filter = new CharacterEncodingFilter();
filter.setEncoding("UTF-8");
filter.setForceEncoding(true);
http.addFilterBefore(filter,CsrfFilter.class);
//rest of your code
}
//rest of your code
}