jsp - HttpServletRequest#getParts()返回一个空列表

标签 jsp servlets

我有以下HTML表单:

<form enctype="multipart/form-data" method="post" action="/myservlet">
    <input type="file" name="mptest">
    <br />
    <input type="submit" value="upload">
 </form>

我有以下基于this answer创建的servlet:
package com.functions;

import java.io.*;
// import java.sql.Connection;
// import java.sql.PreparedStatement;
// import java.sql.ResultSet;
// import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

// import com.functions.utility.DBConnector;
public class restore extends HttpServlet {

    private static final long serialVersionUID = 8097085789553030042L;

    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        System.out.println("--------------------");
        System.out.println(" On restore.java ");
        System.out.println("--------------------");
        try {
            fetchDataFromDB(request, response);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    private void fetchDataFromDB(HttpServletRequest request,
            HttpServletResponse response) throws InterruptedException,
            IllegalStateException, ServletException {
        try {
            System.out.println("Test 1");
            for (Part part : request.getParts()) {
                String filename = getFilename(part);
                System.out.println("Test 2");
                if (filename == null) {
                    System.out.println("Test 3");
                    // Process regular form field (input
                    // type="text|radio|checkbox|etc", select, etc).
                    String fieldname = part.getName();
                    System.out.println(fieldname);
                    String fieldvalue = getValue(part);
                    System.out.println(fieldvalue);
                    // ... (do your job here)
                } else if (!filename.isEmpty()) {
                    System.out.println("Test 4");
                    // Process form file field (input type="file").
                    String fieldname = part.getName();
                    System.out.println(fieldname);
                    filename = filename
                            .substring(filename.lastIndexOf('/') + 1)
                            .substring(filename.lastIndexOf('\\') + 1); // MSIE
                                                                        // fix.
                    InputStream filecontent = part.getInputStream();
                    System.out.println(filecontent);
                    String[] command = new String[] {
                            "C:/Program Files (x86)/MySQL/MySQL Server "
                            + "5.5/bin/mysql",
                            "--user=root", "--password=root", "dummy", "-e",
                            "source "+"C:/Users/John/Desktop/LMS/backup.sql" };
                    Process restore = Runtime.getRuntime().exec(command);
                    int check = restore.waitFor();
                    System.out.println(check);
                }
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    private static String getFilename(Part part) {
        for (String cd : part.getHeader("content-disposition").split(";")) {
            if (cd.trim().startsWith("filename")) {
                return cd.substring(cd.indexOf('=') + 1).trim()
                        .replace("\"", "");
            }
        }
        return null;
    }

    private static String getValue(Part part) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                part.getInputStream(), "UTF-8"));
        StringBuilder value = new StringBuilder();
        char[] buffer = new char[1024];
        for (int length = 0; (length = reader.read(buffer)) > 0;) {
            value.append(buffer, 0, length);
        }
        return value.toString();
    }
}

但是永远不会输入request.getParts()上的for循环。这是怎么引起的,我该如何解决?

最佳答案

如果要使用Servlet 3.0 HttpServletRequest#getParts(),则必须使用 @MultipartConfig 注释Servlet。

@WebServlet(urlPatterns={"/myservlet"})
@MultipartConfig
public class Myservlet extends HttpServlet {

    // ...
}

关于jsp - HttpServletRequest#getParts()返回一个空列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7445296/

相关文章:

java - 包含 jspf 时出错

java - 如何配置项目(取决于 maven/web.xml/servlet API)AJAX 调用不包含项目名称?

java - 在tomcat 6上部署spring应用程序时出现异常

java - 让 JSF View 生成对非 jsf 请求的响应的最佳方法是什么?

java - 使用 Java 将 MySQL 查询结果存储在 ArrayList 中

html - 表格单元格内的 <td> 标记在 IE 7 中创建换行符

jsp - Tomcat 7 不同的行为

java - 如何使用JSP/Servlet将文件上传到服务器?

java - 如何使用Servlet批量上传PDF文件并保存到MySQL中?

java - 无法传递参数apache shiro jsp servlet