使用Spring WebFlow 2.4.0上传文件,参数未绑定

时间:2015-03-13 16:42:24

标签: java spring-security spring-webflow

我正在使用Spring Framework 4.1.5,Spring Security 4.0.0.RC2,Spring Webflow 2.4.0.RELEASE和Tomcat 8.0.15。

我按照webflow documentation中的示例进行操作,但我无法在表单bean中获取该文件。

表格

    <form:form action="${flowExecutionUrl}" method="post" commandName="fileForm" enctype="multipart/form-data">
        <form:input type="file" value="" path="multipartFileUpload"/>
        <button type="submit" name="_eventId_forward"><spring:message code="signup.forward"/></button>
        <sec:csrfInput/>
    </form:form>

表单bean

public class FileForm implements Serializable {
    private static final long serialVersionUID = 1L;

    private transient MultipartFile multipartFileUpload;

    public MultipartFile getMultipartFileUpload() {
        return multipartFileUpload;
    }

    public void setMultipartFileUpload(final MultipartFile multipartFileUpload) {
        this.multipartFileUpload = multipartFileUpload;
    }
}

流程

<view-state id="companyLogo" view="signup/company-logo" model="fileForm">
    <var name="fileForm" class="it.openex.pmcommonw.form.FileForm"/>
    <transition on="back" to="chooseProfile" bind="false" validate="false"/>
    <transition on="forward" to="companyInfo">
        <evaluate expression="userCommonBean.uploadImage(fileForm)"/>
    </transition>
</view-state>

支持对象

@Component
public class UserCommonBean {    
    public static void uploadImage(final FileForm fileForm) throws IOException, ServletException {
        fileForm.getMultipartFileUpload(); // always null!!!
    }
}

multipartResolver

@Bean
public CommonsMultipartResolver filterMultipartResolver() {
    final CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
    multipartResolver.setMaxUploadSize(10 * 1024 * 1024);
    multipartResolver.setMaxInMemorySize(1048576);
    multipartResolver.setDefaultEncoding("UTF-8");
    return multipartResolver;
}

webflow配置

@Configuration
public class WebFlowConfig extends AbstractFlowConfiguration {

    @Autowired
    TilesViewResolver viewResolver;

    @Bean
    public FlowDefinitionRegistry flowRegistry() {
        return getFlowDefinitionRegistryBuilder()
            .setFlowBuilderServices(flowBuilderServices())
            .setBasePath("/WEB-INF/flows/")
            .addFlowLocation("signup.xml", UrlMap.SIGNUP_WEBFLOW)
            .addFlowLocation("user-edit.xml", UrlMap.PROFILE_EDIT_WEBFLOW)
            .build();
    }

    @Bean
    public FlowExecutor flowExecutor() {
        return getFlowExecutorBuilder(flowRegistry()).build();
    }

    @Bean
    public FlowHandlerAdapter flowHandlerAdapter() {
        final FlowHandlerAdapter flowHandlerAdapter = new FlowHandlerAdapter();
        flowHandlerAdapter.setFlowExecutor(flowExecutor());
        return flowHandlerAdapter;
    }

    @Bean
    public FlowHandlerMapping flowHandlerMapping() {
        final FlowHandlerMapping flowHandlerMapping = new FlowHandlerMapping();
        flowHandlerMapping.setFlowRegistry(flowRegistry());
        // this has to be less than -1
        flowHandlerMapping.setOrder(-2);
        return flowHandlerMapping;
    }

    @Bean
    public MvcViewFactoryCreator mvcViewFactoryCreator() {
        final MvcViewFactoryCreator mvcViewFactoryCreator = new MvcViewFactoryCreator();
        final List<ViewResolver> viewResolvers = Collections.singletonList(viewResolver);
        mvcViewFactoryCreator.setViewResolvers(viewResolvers);
        return mvcViewFactoryCreator;
    }

    @Bean
    public FlowBuilderServices flowBuilderServices() {
        return getFlowBuilderServicesBuilder().setViewFactoryCreator(mvcViewFactoryCreator())
            .setValidator(localValidatorFactoryBean()).build();
    }

    @Bean
    public LocalValidatorFactoryBean localValidatorFactoryBean() {
        return new LocalValidatorFactoryBean();
    }
}

在Tomcat的context.xml内,我已经添加了allowCasualMultipartParsing="true"

调试应用程序我可以看到请求中的文件数据,如果我尝试将表单发布到普通控制器,我可以得到它。

我还试图删除Spring Security,但它仍然无法在Spring WebFlow中运行。

在requestParameters对象中,只有3个对象:

  • 执行
  • _eventid_forward
  • _csrf

日志中有一些相关的行

DEBUG 2015-03-13 18:03:15,053: org.springframework.web.multipart.support.MultipartFilter - Using MultipartResolver 'filterMultipartResolver' for MultipartFilter
DEBUG 2015-03-13 18:03:15,053: org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'filterMultipartResolver'
DEBUG 2015-03-13 18:03:15,053: org.springframework.web.multipart.support.MultipartFilter - Resolving multipart request [/registrazione] with MultipartFilter
DEBUG 2015-03-13 18:03:15,060: org.springframework.web.multipart.commons.CommonsMultipartResolver - Found multipart file [multipartFileUpload] of size 469217 bytes with original filename [PoliziaMunicipale.png], stored in memory
....
DEBUG 2015-03-13 18:03:15,072: org.springframework.binding.mapping.impl.DefaultMapper - Beginning mapping between source [org.springframework.webflow.core.collection.LocalParameterMap] and target [it.openex.pmcommonw.form.FileForm]
DEBUG 2015-03-13 18:03:15,072: org.springframework.binding.mapping.impl.DefaultMapping - Adding mapping result [TargetAccessError@34bc31ea mapping = parameter:'execution' -> execution, code = 'propertyNotFound', error = true, errorCause = org.springframework.binding.expression.PropertyNotFoundException: Property not found, originalValue = 'e1s2', mappedValue = [null]]
DEBUG 2015-03-13 18:03:15,072: org.springframework.binding.mapping.impl.DefaultMapper - Completing mapping between source [org.springframework.webflow.core.collection.LocalParameterMap] and target [it.openex.pmcommonw.form.FileForm]; total mappings = 1; total errors = 1

multipartFileUpload属性未绑定在FileForm bean中。

我不确定它是否有用,但在第52行org.springframework.webflow.context.servlet.HttpServletRequestParameterMap

if (request instanceof MultipartHttpServletRequest) {
        // ... process multipart data
    }

它未通过检查,因为请求是org.springframework.security.web.context.HttpSessionSecurityContextRepository$Servlet3SaveToSessionRequestWrapper

的实例

更新1

我可以确认multipartRequest.getFile(“file”)也可以。

我无法启用org.springframework.web.multipart.support.MultipartFilter过滤器。

如果启用了multipartRequest,则StandardMultipartHttpServletRequest的实例包含Servlet3SecurityContextHolderAwareRequestWrapper,包裹Servlet3SaveToSessionRequestWrapper,最后包含一个无法访问的DefaultMultipartHttpServletRequest,其中包含我需要的multipartFile,但是无法得到它。

禁用它我能够得到它因为multipartRequest成为DefaultMultipartHttpServletRequest的实例,但是没有文件验证,并且不遵守CommonsMultipartResolver的maxUploadSize限制。

另外如果Tomcat因为Tomcat的maxPostSize限制文件太大而引发异常,我的CustomAccessDeniedHandler会抓住异常,因为它的类型为org.springframework.security.access.AccessDeniedException,错误消息为{{1} }。

查看请求对象,我可以看到原始的Tomcat异常Invalid CSRF Token 'null' was found on the request parameter '_csrf' or header 'X-CSRF-TOKEN'.。似乎没有什么可以正确处理它,但是,正如我所说,如果我启用MultipartFilter,我无法获取文件。

1 个答案:

答案 0 :(得分:5)

我们遇到了同样的问题,因为我们在Web应用程序中使用Spring Security 4.xx。 问题是org.springframework.security.web.context.HttpSessionSecurityContextRepository$Servlet3SaveToSessionRequestWrapper不是org.springframework.web.multipart.MultipartHttpServletRequest的实例,而是包含一个ClassCastException。强制转换不起作用,if (request instanceof MultipartHttpServletRequest) { // ... process multipart data } 将会发生。

这就是为什么

true

永远不可能是org.springframework.web.multipart.support.StandardMultipartHttpServletRequest

我们的想法是从原生HttpServletRequest创建一个public String fileUpload(RequestContext requestContext) { final ServletExternalContext context = (ServletExternalContext) requestContext.getExternalContext(); final MultipartHttpServletRequest multipartRequest = new StandardMultipartHttpServletRequest((HttpServletRequest)context.getNativeRequest()); final File file = multipartRequest.getFile("file"); fileUploadHandler.processFile(file); //do something with the submitted file } ,然后就可以了。

在我们的WebApp中,我们使用Spring Webflow documentation Section 6.5.1. Invoking a POJO action中指示的Pojo动作。

我们的解决方法:

PojoAction.java

<action-state id="upload-action">
    <evaluate expression="pojoAction.uploadFile(flowRequestContext)"/>
    <transition to="show"/>
</action-state>

在flow.xml中,我们有一个这样的动作状态:

    <filter>
        <filter-name>csrfFilter</filter-name>
        <filter-class>
            org.springframework.web.filter.DelegatingFilterProxy
        </filter-class>
        <async-supported>true</async-supported>
    </filter>
    <filter-mapping>
        <filter-name>csrfFilter</filter-name>
        <url-pattern>/*</url-pattern>
     </filter-mapping>

     <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>
           org.springframework.web.filter.DelegatingFilterProxy
        </filter-class>
      </filter>
      <filter-mapping>
         <filter-name>springSecurityFilterChain</filter-name>
         <url-pattern>/*</url-pattern>
         <dispatcher>REQUEST</dispatcher>
         <dispatcher>ERROR</dispatcher>
      </filter-mapping>

在这种情况下,不需要绑定到模型。 我希望它有所帮助!

根据更新1

在web.xml中,CSRF-Protection过滤器必须在SpringSecurityFilterChain之前声明。

在我们的应用程序中,web.xml看起来像这样

{{1}}