在我的项目中,Encodingfilter是用WEB.XML编写的。但是我想在没有WEB.XML的情况下编写它,我只想在Java类中编写。
我的WEB.XML中的 Encodingfilter
如何在没有WEB.xml的JAVA类中编写它
<filter>
<filter-name>encodingFilter</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>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
我正确编写的编码过滤器?
public class ServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Value("${spring.servlet.multipart.max-file-size}")
private int maxFileSize;
@Value("${spring.servlet.multipart.max-request-size}")
private int maxRequestSize;
@Autowired
private Environment environment;
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[]{HibernateConfig.class/*, SecurityConfig.class*/};
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[]{WebMvcConfig.class};
}
@Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
@Override
protected Filter[] getServletFilters() {
CharacterEncodingFilter filter = new CharacterEncodingFilter();
filter.setEncoding("UTF-8");
filter.setForceEncoding(true);
return new Filter[]{filter};
}
}
答案 0 :(得分:1)
您可以使用org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer
:
public class MyWebInitializer extends
AbstractAnnotationConfigDispatcherServletInitializer {
//...
@Override
protected Filter[] getServletFilters() {
CharacterEncodingFilter filter = new CharacterEncodingFilter();
filter.setEncoding("UTF-8");
filter.setForceEncoding(true);
return new Filter[]{filter};
}
}