如何使setMultipartConfig适用于动态添加的servlet?

时间:2013-10-10 10:55:42

标签: java java-ee servlets jboss servlet-3.0

当我调用setMultipartConfig到动态添加的servlet request.getParts();时,它应该包含上传的文件时返回一个空集合。

JSP

<!DOCTYPE html>
<html>
  <head>
      <meta charset="utf-8">
  </head>
  <body>
    <form action="/{context here}/hello" method="post" enctype="multipart/form-data">
      <input type="file" name="avatar">
      <button>Go</button>
    </form>
  </body>
</html>

servlet:

@WebServlet( "/hello" )
public class HelloServlet extends HttpServlet {
    private static final long serialVersionUID = 1;

    @Override
    protected void doGet( HttpServletRequest request, HttpServletResponse response )
    throws ServletException, IOException {
        request.getRequestDispatcher( "/hello.jsp" ).forward( request, response );
    }
    @Override
    protected void doPost( HttpServletRequest request, HttpServletResponse response )
    throws IOException, ServletException {
        // Here an empty collection even if I do select a file...
        request.getParts();
    }
}

动态添加的侦听器

@WebListener
public class HelloListener implements ServletContextListener {
    @Override
    public void contextInitialized( ServletContextEvent event ) {
        Dynamic registered = event.getServletContext().addServlet( "hello", HelloServlet.class );
        registered.addMapping( "/hello" );
        registered.setMultipartConfig( getMultiPartConfig() );
    }
    @Override
    public void contextDestroyed( ServletContextEvent event ) {}

    private MultipartConfigElement getMultiPartConfig() {
        String location = "";
        long maxFileSize = -1;
        long maxRequestSize = -1;
        int fileSizeThreshold = 0;
        return new MultipartConfigElement(
            location,
            maxFileSize,
            maxRequestSize,
            fileSizeThreshold
        );
    }
}

如何让multipart配置与dinamically添加的servlet一起使用?

使用: JBoss EAP 6.1

1 个答案:

答案 0 :(得分:0)

删除@WebServlet( "/hello" )声明解决了问题