代码方式配置springmvc的字符集过滤器

之前一直用的xml方式配置

<filter>
        <filter-name>encoding</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
    </filter>
<filter-mapping>
        <filter-name>encoding</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

一直不知道代码怎么配置,现在有了

// 继承AbstractAnnotationConfigDispatcherServletInitializer
@Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        String filterName = "myfilter";
        FilterRegistration.Dynamic filterRegistration = servletContext.addFilter(filterName, new MyFilter());
        filterRegistration.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), false, "/*");
        //父类的方法一定要调用,否则getRootConfigClasses与getServletConfigClasses等方法都会失效
        super.onStartup(servletContext);
    }

相关推荐