Issue
In my project, the Encodingfilter is written in the WEB.XML. But I want to write it without WEB.XML, i want write in just java class.
Encodingfilter in my WEB.XML
How can you write it in JAVA class without WEB.xml
<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>
Encoding filter I correctly wrote?
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};
}
}
Solution
You can use 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};
}
}
Answered By - user10871691