如何使用WebApplicationInitializer配置主面FileUploadFilter

时间:2013-12-19 19:31:14

标签: spring jsf-2 spring-java-config

我一直在将一个有效的Primefaces JSF 2应用程序从spring XML配置移植到更新的Spring 3.2 Java Configuration模型。 所以同时我也决定移植web.xml配置。事情已经相当不错但我似乎陷入了一件特别的事情。 我的根本问题是如何在实现WebApplicationInitializer的类中为过滤器设置init parms。

所以我有web.xml的以下部分

 <filter>
    <filter-name>PrimeFaces FileUpload Filter</filter-name>
    <filter-class>
        org.primefaces.webapp.filter.FileUploadFilter
    </filter-class>
    <init-param>
        <!-- we set the threshold size to be exactly 1 megabyte -->
        <param-name>thresholdSize</param-name>
        <param-value>1048576</param-value>
    </init-param>
    <init-param>
        <!-- this is the location for the upload  -->
        <param-name>uploadDirectory</param-name>
        <!-- we select the system tmp directory for this -->
        <param-value>/tmp/myapp/uploads</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>PrimeFaces FileUpload Filter</filter-name>
    <servlet-name>facesServlet</servlet-name>
</filter-mapping>

在我实现WebApplicationInitializer的ApplicationInitializer中,我定义了一个过滤器。但我看不出如何为thresholdSize和uploadDirectory设置init参数 有这么简单的方法吗?

由于

1 个答案:

答案 0 :(得分:2)

好的我明白了。我创建了自己的FilterConfig接口实现,并在创建过滤器后通过过滤器上的init方法传递它。

对于那些感兴趣的人是代码

 private void setupFileUploadFilter(ServletContext container) {
    try {
        // create the filter config for the file upload filter
        FilterConfig filterConfig = setupFileUpLoadFilterConfig(container);

        // create the filter
        FileUploadFilter fileUploadFilter = new FileUploadFilter();

        // initialize the file upload filter with the specified filter config
        fileUploadFilter.init(filterConfig);

        // register the filter to the main container
        FilterRegistration.Dynamic fileUploadFilterReg = container.addFilter("PrimeFaces FileUpload Filter", fileUploadFilter);

        // map it for all patterns
        fileUploadFilterReg.addMappingForUrlPatterns(null, false, "/*");

        // add a mapping to the faces Servlet
        fileUploadFilterReg.addMappingForServletNames(null, false, "facesServlet");

    } catch (ServletException e) {
        e.printStackTrace();
    }
}

/**
 * create the initialization parameters for the file upload filter
 *
 * @param container the main container
 * @return the created filter config
 */
private FilterConfig setupFileUpLoadFilterConfig(ServletContext container) {
    CustomFilterConfig filterConfig = new CustomFilterConfig(container, "PrimeFaces FileUpload Filter");

    // add the size parameter which is 1 Megabyte
    filterConfig.addInitParameter("thresholdSize", "1048576");

    // add the size parameter
    filterConfig.addInitParameter("uploadDirectory", "/tmp/myapp/uploads");

    return filterConfig;
}