我正在开发一个Web应用程序。我有一个enctype =“multipart / form-data”的jsp,当我提交请求时,我无法在servlet中获取请求参数。
getParameter()调用都将返回null。问题是如何克服这个问题?
当它没有被输入时,这段代码工作正常。我知道这已被多次询问,但我没有找到任何直接的答案
JSP
<form action="upload" method="post" enctype="multipart/form-data">
<input type="file" name="uploadfile[]" id="uploadfile" size="50" multiple="true" />
<br/><br/>
<input type="hidden" name ="e_id" value= <%=userBean.getEid%> />
<input type="hidden" name ="Uid" value= <%=userBean.getUid()%> />
<input type="submit" name ="button1" value="Upload" />
</form>
Servlet的
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
int e_id =0;
String uid = null;
HttpSession session1 = request.getSession(true);
if(ServletFileUpload.isMultipartContent(request)){//process only if its multipart content
try
{
List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
for(FileItem item : multiparts)
{
if(!item.isFormField())
{
String name = new File(item.getName()).getName();
item.write( new File(UPLOAD_DIRECTORY + File.separator + name));
e_id = Integer.parseInt(request.getParameter("e_id"));
uid = request.getParameter("Uid");
}
else {}
...
您需要使用@MultipartConfig
注释您的servlet并获取您使用的参数的值:
Part idPart = req.getPart("e_id");
try (Scanner scanner = new Scanner(idPart.getInputStream())) {
String idValue = idPart.nextLine(); // read from the part
}
我在github上有一个project,有一个如何使用它的例子: