首页 > 解决方案 > 简单的 Jetty/JSF 文件上传不会提交

问题描述

我已经看过这个和相关的票无济于事。

我有,看起来最简单的例子

<h:form enctype="multipart/form-data"  prependId="false">
<h:outputText value="File: "></h:outputText>
<h:inputFile value="#{configUploadController.uploadedFile}"  />
<h:commandButton value="Save" type="submit" action="#{configUploadController.uploadFile}" style="color: red;"></h:commandButton>
</h:form>

我在我的uploadFile方法中设置了一个断点,但它从来没有被击中。当我enctype从表单中删除它确实尝试提交但随后我得到明显的错误......

javax.servlet.ServletException: Content-Type != multipart/form-data

为了完整起见,我删除了<h:inputFile>andenctype并且可以看到我的断点被击中。当我设置它时enctype,它不会到达断点。但是,当我设置为乱码时,它确实达到了断点:(text/plainenctype

我是否在某处缺少依赖项或配置?

万一这很重要,我的 web.xml ......

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
    version="3.1">

    <!-- File(s) appended to a request for a URL that is not mapped to a web 
        component -->
    <welcome-file-list>
        <welcome-file>status.xhtml</welcome-file>
    </welcome-file-list>

    <context-param>
        <param-name>com.sun.faces.expressionFactory</param-name>
        <param-value>com.sun.el.ExpressionFactoryImpl</param-value>
    </context-param>

    <listener>
        <description>Initializes Oracle JSF</description>
        <listener-class>com.sun.faces.config.ConfigureListener</listener-class>
    </listener>

    <!-- Define the JSF servlet (manages the request processing life cycle for 
        JavaServer Faces) -->
    <servlet>
        <servlet-name>faces-servlet</servlet-name>
        <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
        <load-on-startup>0</load-on-startup>
    </servlet>

    <!-- Map following files to the JSF servlet -->
    <servlet-mapping>
        <servlet-name>faces-servlet</servlet-name>
        <url-pattern>*.xhtml</url-pattern>
    </servlet-mapping>


</web-app>

标签: jsfjetty

解决方案


实际问题不是使用 servlet(根据其他答案),而是 Jetty 需要为每个多部分请求设置多部分配置。

执行此操作的简单方法是添加一个过滤器,根据需要添加它,例如。

public class LoginFilter implements Filter {

  private static final String MULTIPART_FORM_DATA = "multipart/form-data";
  private static final MultipartConfigElement MULTI_PART_CONFIG =
        new MultipartConfigElement(System.getProperty("java.io.tmpdir"));

  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
        throws IOException, ServletException {

    HttpServletRequest httpServletRequest = (HttpServletRequest) request;
    HttpServletResponse httpServletResponse = (HttpServletResponse) response;

    String contentType = request.getContentType();
    if (contentType != null && contentType.startsWith(MULTIPART_FORM_DATA))
        request.setAttribute(Request.__MULTIPART_CONFIG_ELEMENT, MULTI_PART_CONFIG);

    filterChain.doFilter(request, response);
  }
}

也可以看看:


推荐阅读