java - 多部分/表单参数即将为空

标签 java jsp servlets apache-commons

我正在尝试获取由表单编码类型“multipart/form-data”发送的请求参数。我正在使用 apache commons fileupload。

我的代码如下。

FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List items = upload.parseRequest(req);
Iterator uploadIterator = items.iterator();

while(uploadIterator.hasNext()){
FileItem uploadedItem = (FileItem) uploadIterator.next();


if (uploadedItem.isFormField()){

  if (uploadedItem.getFieldName().equals("name")){
    name = uploadedItem.getString();
  }
}else{
  //Uploaded files comes here
}

表单的 HTML 代码是:

<form name="form" id="form" method="post" action="ServletIncluirEvento"
    enctype="multipart/form-data">
... //Here comes a lot of inputs (I changed the name of the attribute because I am from Brazil and the names are in portuguese)

<select size="9" id="idOpcoesSelecionadas" name="opcoesSelecionadas" multiple style="width: 100%;">
                                            <%  
 it =  colecaoUsuarioSelecionado.iterator();                             String name= "";
 while (it.hasNext()) {
 usuario = (Usuario) it.next();
 name += usuario.getName() + "/"; %>
 <option value="<%=usuario.getLogin()%>">
    <%=usuario.getName()%>
 </option>
<%
  }
%></select>

<input type="hidden" value="<%=name%>" name="name" />

即便如此,参数仍为空。

有人知道怎么解决吗?

提前致谢

最佳答案

修改调用方法equals:

"name".equals(uploadedItem.getFieldName());

一般来说,我会更清楚地重写您的代码:

FileItemFactory factory = new DiskFileItemFactory();
FileUpload upload = new ServletFileUpload(factory);
List<FileItem> items = upload.parseRequest(req);
for (FileItem uploadedItem : items) {
    if (uploadedItem.isFormField()) {
        String fieldName = uploadedItem.getFieldName();

        if ("name".equals(fieldName)){
           name = uploadedItem.getString();
        }
    } else {
        // process file field
    }    
}

这让代码变得更容易理解。调用两次方法 getFieldName() 是没有意义的。并使用 Generic .它通过在编译时检查类型来增加代码的稳定性。获取当前对象时无需强制转换。

关于java - 多部分/表单参数即将为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11959510/

相关文章:

java - TestNG 未在 eclipse 上运行测试

java - Spring security 登录后如何跳转到另一个页面

java - 无法使用 JSP 连接到 mySQL 数据库

java - HttpURLConnection 和浏览器连接之间的区别

java - 使用Powershell用tomcat servlet-api.jar编译java

Java堆外内存和大页面

java - 使用 Robolectrics 和 Mockito 来模拟/ stub 函数调用发出 http 请求,但它不起作用

java - 重新加载jsp页面时出现字节限制超出问题?

java - 如何从我的 war 中访问文本文件

java - Android SQLite DB 适配器更新 DB