尝试从多个选择字段中获取值。但只能检索第一个值吗?
在普通形式中,使用for循环迭代字段名称然后将值添加到数组没有问题。
但是当使用多部分请求表单时,无法理解如何获得相同的值?
例如,
的servlet:
String sctype = null, sfieldname = null, sname = null;
FileItemIterator iterator;
FileItemStream item = null;
InputStream stream = null;
try{
ServletFileUpload upload = new ServletFileUpload();
iterator = upload.getItemIterator(request);
while (iterator.hasNext()) { // iterate over form fields
item = iterator.next();
stream = item.openStream();
String fieldname = item.getFieldName();
if (item.isFormField()) { // Problem here
String value = Streams.asString(stream);
//String[] valueArray = Streams.asString(stream) //test
if (fieldname.equals("title")){
title = value;
}
if (fieldname.equals("multipleSelect")){
//multipleSelect = valueArray[]; //test
multipleSelect = value; // only gives one value :S
} else { // gets values from uploaded files
sfieldname = item.getFieldName();
sname = item.getName();
sctype = item.getContentType();
stream.close();
}
} // if form
} // while
} ....( try catch block/finally, etc)...
JSP / HTML
<form action="FormServlet" method="post" enctype="multipart/form-data">
<textarea class="form-control" name="title" placeholder="Title"></textarea>
<select class="form-control" name="multipleSelect" multiple="multiple">
<option value="ring">Ring</option>
<option value="necklace">Necklace</option>
</select>
<input type="file" name="file1" size="50" multiple>
</form>
希望很清楚。任何指针都非常赞赏。谢谢你的时间。
答案 0 :(得分:2)
修改:
解析的结果是文件列表,每个文件项都实现了FileItem接口。
e.g。
'use strict';
(function () {
var StoreAPI = require('Store');
module.exports = {
getBooks: function (event, context,callback) {
var books;
StoreAPI.getAll('books', function(err,data){
console.log(data);
callback({
path: data.path,
error: false,
errorCode: 0,
body: {
books : data
}
});
});
}
};
} ());
所以你要做的就是逐个获取所有值,然后将其转换为所需的数据类型(即 - 收集List中的所有内容并将其转换为String [] :))
答案 1 :(得分:1)
以下是我使用的简单解决方法
在<form>
和</form>
之间创建一个隐藏文本字段,用于将下拉列表的选定项值存储为分隔字符串(本例中为逗号)。 (即:&#39;环,项链&#39)
<input type="hidden" id="multipleSelectValues" name="multipleSelectValues" />
添加客户端JavaScript / JQuery..etc,以便在更改选定值时,隐藏文本字段中的文本将更新。
$("select[name='multipleSelect']").change(function() {
var arr = $("select[name='multipleSelect']").val(); //automatically creates an array of selected values
var foo = arr.join(","); //creates a comma delimited string (i.e:'ring,necklace')
$( "#multipleSelectValues" ).val(foo); //update hidden field value
});
在servlet中,可以使用字符串split()
命令解析值。
if (fieldname.equals("multipleSelect")){
String[] valueArray = value.split(","); //split string by ,
//do your array stuff here, for example
for (String individualValue: valueArray ) {
//play with individual dropdown item here, for example
System.out.println(individualValue);
}
}
答案 2 :(得分:0)
我发现您提供的代码没有任何问题。
代码运行正常,我认为这可能是commons jar版本的一个问题。