在Spring bean中未调用p:fileUpload方法

时间:2019-01-04 11:43:19

标签: ajax spring jsf primefaces

此问题涉及使用Primefaces上传在Spring Framework中上传和处理CSV数据,以便在数据库中创建新条目。

我已经在Primefaces的模板上构建了XHTML代码。当我单击Submit按钮时,应该调用uploadDevices方法,但是我发现从未输入过该方法。当我删除ajax =“ false”语句时,将调用该方法,但会在Inputstream上引发Nullpointer异常,因此显然未收到该文件。

有人对做什么有建议吗? ajax语句做什么,从而阻止了该方法的调用?

非常感谢您的帮助。

devices.xhtml

<h:form enctype="multipart/form-data" style="margin-bottom:20px">
    <p:growl id="messages" showDetail="true" />

    <p:fileUpload value="#{fileUploadView.file}" ajax="false" mode="simple" skinSimple="true" allowTypes="/(\.|\/)(csv)$/"/>

    <p:commandButton value="Submit" ajax="false" action="#{fileUploadView.uploadDevices()}" disabled="false" />
</h:form>

FileUploadView.java

@Component
@Scope("view")
public class FileUploadView {

private UploadedFile file;
// plus getter and setter

@Autowired
private DeviceService deviceService;

private Device device;

public void uploadDevices() { 
    final CSVParser parser = new CSVParserBuilder().withSeparator(',').withIgnoreQuotations(true).build();
    final BufferedReader fileReader = new BufferedReader(new InputStreamReader(file.getInputstream())); 

}

2 个答案:

答案 0 :(得分:0)

人们从用户指南中忘记了两个常见的事情。不要忘记“ Faces Servlet”必须与web.xml中的Faces Servlet的Servlet名称相匹配

  1. 在您的web.xml中

    <!-- Primefaces required for FileUploads to work -->
    <filter>
       <filter-name>PrimeFaces FileUpload Filter</filter-name>
       <filter-class>org.primefaces.webapp.filter.FileUploadFilter</filter-class>
    </filter>
    <filter-mapping>
       <filter-name>PrimeFaces FileUpload Filter</filter-name>
       <servlet-name>Faces Servlet</servlet-name>
    </filter-mapping>
    
  2. 在您的pom.xml中添加Commons Upload依赖项。

        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.3</version>
        </dependency>
    

答案 1 :(得分:0)

好的,最后解决我的问题的是在Servlet配置中添加这些方法,现在Upload可以正常工作了:

@Bean
public ServletRegistrationBean facesServletRegistratiton() {
ServletRegistrationBean registration = new ServletRegistrationBean(new FacesServlet(), new String[] { "*.xhtml" });
registration.setName("Faces Servlet");
registration.setLoadOnStartup(1);
return registration;
}

@Bean
public FilterRegistrationBean facesUploadFilterRegistration() {
FilterRegistrationBean registrationBean = new FilterRegistrationBean(new FileUploadFilter(), facesServletRegistratiton());
registrationBean.setName("PrimeFaces FileUpload Filter");
registrationBean.addUrlPatterns("/*");
registrationBean.setDispatcherTypes(DispatcherType.FORWARD, DispatcherType.REQUEST);
return registrationBean;
}

@Bean
public ServletContextInitializer servletContextInitializer() {
return new ServletContextInitializer() {
    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
    servletContext.setInitParameter("primefaces.UPLOADER", "commons");
    }
};
}