H:的commandButton不点火动作,如果H:形式具有ENCTYPE =“多部分/格式数据”(

2019-07-18 01:05发布

JSF:1.2

服务器:Weblogic

我想实现多文件上传。 当我需要给IE7的支持,所以我不能使用HTML5输入文件。 所以我打算添加一个按钮,在单击它会在页面中添加输入文件。

主要是我已经开始用的ADF Faces我的工作。 但是,这并没有奏效。 这是在行为意想不到的方式。

我也曾尝试战斧的文件上传组件,但问题是这个组件从后端添加新的文件上传后,先前创建的文件上传域均得到空的; 不是UploadedFile实例。 但是,这不能满足我的要求。 当我需要显示在文件上传所有的路径,直到最后提交表单按钮被点击。

然后,我把Apache的百科全书文件上传的帮助。

我已经用纯JSP尝试这样做,阿帕奇文件上传和运作良好。

但我想用阿帕奇文件上传JSF实现它,当我试图做到这一点,开始引起问题。

该JSPX页面下面给出:

<?xml version='1.0' encoding='utf-8'?>
<jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" version="2.1"
          xmlns:f="http://java.sun.com/jsf/core"
          xmlns:h="http://java.sun.com/jsf/html">
  <jsp:output omit-xml-declaration="true" doctype-root-element="HTML"
              doctype-system="http://www.w3.org/TR/html4/loose.dtd"
              doctype-public="-//W3C//DTD HTML 4.01 Transitional//EN"/>
  <jsp:directive.page contentType="text/html;charset=utf-8"/>
  <f:view>
    <html>
      <head>
        <meta http-equiv="Content-Type"
              content="text/html; charset=utf-8"/>
        <title>home</title>
      </head>
      <body>
        <h:form enctype="multipart/form-data">
            <input type="file" name="file"/>
            <h:commandButton value="Upload" action="#{uploadBean.upload}" />
        </h:form>
      </body>
    </html>
  </f:view>
</jsp:root>

我创建了一个过滤器,因为我不能得到从适当多要求action的事件。

在web.xml是:

<?xml version = '1.0' encoding = 'windows-1252'?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
         version="2.5" xmlns="http://java.sun.com/xml/ns/javaee">
  <context-param>
    <param-name>javax.faces.STATE_SAVING_METHOD</param-name>
    <param-value>server</param-value>
  </context-param>
  <filter>
    <filter-name>UploadFilter</filter-name>
    <filter-class>com.edfx.massupload.filter.UploadFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>UploadFilter</filter-name>
    <servlet-name>Faces Servlet</servlet-name>
  </filter-mapping>
  <servlet>
    <servlet-name>Faces Servlet</servlet-name>
    <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>/faces/*</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>/home.jspx</welcome-file>
  </welcome-file-list>
</web-app>

该UploadFilter:

import java.io.IOException;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;


public class UploadFilter implements Filter {
    private FilterConfig _filterConfig = null;

    public void init(FilterConfig filterConfig) throws ServletException {
        _filterConfig = filterConfig;
    }

    public void destroy() {
        _filterConfig = null;
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        System.out.println("Filter");
        if (!(request instanceof HttpServletRequest)) {
            chain.doFilter(request, response);
            return;
        }

        HttpServletRequest httpRequest = (HttpServletRequest)request;

        boolean isMultipartContent = ServletFileUpload.isMultipartContent(httpRequest);

        if (!isMultipartContent) {
            chain.doFilter(request, response);
            return;
        }

        long maxFileSize = (1024 * 1024 * 1024);
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setHeaderEncoding("UTF-8");
        upload.setSizeMax(maxFileSize);
        upload.setFileSizeMax(maxFileSize);

        try {
            List<FileItem> items = upload.parseRequest(httpRequest);
            System.out.println(items.size());
            List<FileItem> files = new ArrayList<FileItem>();            
            for (FileItem item : items) {
                if (!item.isFormField()) {
                    files.add(item);
                }
            }

            httpRequest.setAttribute("files", files);
        } catch (FileUploadException ex) {
            ex.printStackTrace();
        }        

        chain.doFilter(request, response);
    }
}

最后是管理的bean:

import javax.faces.context.FacesContext;

import javax.servlet.http.HttpServletRequest;

public class UploadBean {
    public UploadBean() {
        super();
    }

    public String upload() {
        System.out.println("====JYM");
        HttpServletRequest httpRequest = (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
        System.out.println(httpRequest.getAttribute("files"));
        return "";
    }
}

我的目标是由JavaScript或jQuery的,这在JSP行之有效动态添加的输入文件中的字段,我想,在JSF。

如果删除了enctype="multipart/form-data"h:form则动作方法执行,否则不是。

任何的建议是对我很有帮助。

Answer 1:

这里,

for (FileItem item : items) {
    if (!item.isFormField()) {
        files.add(item);
    }
}

你是忽略所有的表单域,如按钮本身。 如果继续这样的要求,JSF将没有任何线索,一个按钮被被调用,因此不排队任何行动。

您需要将添加else收集所有表单域的Map<String, String[]>与包裹请求HttpServletRequestWrapper委托给上所有的地图getParameterXxx()的调用,并最终继续包装的请求过滤器链。 这样,JSF会发现,按钮被调用,然后排队到适当的行动。



Answer 2:

作为@BalusC指示:

import java.io.IOException;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;


public class UploadFilter implements Filter {
    private FilterConfig filterConfig = null;

    public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig = filterConfig;
    }

    public void destroy() {
        this.filterConfig = null;
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        if (!(request instanceof HttpServletRequest)) {
            chain.doFilter(request, response);
            return;
        }

        HttpServletRequest httpRequest = (HttpServletRequest)request;

        boolean isMultipartContent = ServletFileUpload.isMultipartContent(httpRequest);

        if (!isMultipartContent) {
            chain.doFilter(request, response);
            return;
        }        

        try {
            DiskFileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            upload.setHeaderEncoding("UTF-8");
            upload.setSizeMax(-1);

            List<FileItem> items = upload.parseRequest(httpRequest);
            final Map<String, String[]> parameterMap = new HashMap<String, String[]>();

            for (FileItem item : items) {
                if (item.isFormField()) {
                    processFormField(item, parameterMap);
                } else {
                    processFileField(item, httpRequest);
                }
            }

            chain.doFilter(new HttpServletRequestWrapper(httpRequest) {

                    public Map<String, String[]> getParameterMap() {
                        return parameterMap;
                    }

                    public String[] getParameterValues(String name) {
                        return (String[])parameterMap.get(name);
                    }

                    public String getParameter(String name) {
                        String[] params = getParameterValues(name);
                        if (params == null) {
                            return null;
                        }
                        return params[0];
                    }

                    public Enumeration<String> getParameterNames() {
                        return Collections.enumeration(parameterMap.keySet());
                    }
                }, response);
        } catch (Exception ex) {
            ServletException servletException = new ServletException();
            servletException.initCause(ex);
            throw servletException;
        }
    }

    private void processFormField(FileItem formField, Map<String, String[]> parameterMap) {
        String name = formField.getFieldName();
        String value = formField.getString();
        String[] values = parameterMap.get(name);

        if (values == null) {
            parameterMap.put(name, new String[] { value });
        } else {
            int length = values.length;
            String[] newValues = new String[length + 1];
            System.arraycopy(values, 0, newValues, 0, length);
            newValues[length] = value;
            parameterMap.put(name, newValues);
        }
    }

    private void processFileField(FileItem fileField, HttpServletRequest request) {
        if (request.getAttribute(fileField.getFieldName()) == null) {
            List<FileItem> fileFields = new ArrayList<FileItem>(0);
            fileFields.add(fileField);
            request.setAttribute(fileField.getFieldName(), fileFields);
        } else {
            List<FileItem> fileFields = (List<FileItem>)request.getAttribute(fileField.getFieldName());
            fileFields.add(fileField);
        }
    }
}

因为我将有多个输入文件组件; 所以我用List存储在该方法中的所有文件字段processFileField ,然后把它设置为request



文章来源: h:commandButton is not firing action if the h:form has enctype=“multipart/form-data”