使用jsp和servlet将文件上载到服务器和解析表单时出现问题

时间:2014-06-03 16:58:25

标签: java jsp servlets

我尝试将文件上传到服务器并从表单粘贴数据并写入数据库元组。但是没有任何事情发生/我在这方面有点新,所以抱歉愚蠢的错误。 这里来自upload.jsp

<form action="controller" method="post" enctype="multipart/form-data">
      <input type="hidden" name="command" value="addLabWork">
      <input type="hidden" name="exactCurriculumId" value="${exactCurriculum.id}"/>
      <input type="hidden" name="number" value="${labs.size() + 1}">
      <input type="text" name="title" placeholder="Назва лабораторної роботи"/>
      <input type="number" name="credits" placeholder="Бали"/>
      <input type="file" name="taskFile" placeholder="Файл завдання"/>
      <input type="submit" value="Додати"/>
</form>

next - 我尝试从servlet中的表单获取参数,将文件写入文件夹并使用hibernate将实体写入db。

String LABS_FOLDER = "C:\\uploads";
String page = ConfigurationManager.getInstance()
            .getProperty(ConfigurationManager.EXACT_CURRICULUM_LAB_WORKS_PAGE);

String filePath = null;

FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);

Map<String, String> params = new HashMap<>();

try {
    File file;
    List<FileItem> fields = upload.parseRequest(request);
    Iterator<FileItem> it = fields.iterator();
    for (FileItem fileItem : fields) {                

        if (fileItem.isFormField()) {
            params.put(fileItem.getFieldName(), fileItem.getString());

        } else {
            String filename = fileItem.getName();
            filePath = LABS_FOLDER + File.separator + filename;
            file = new File( filePath);
            fileItem.write(file);  
        }
    }

} catch (FileUploadException ex) {
    Logger.getLogger(AddLaboratoryWorkCommand.class.getName()).log(Level.SEVERE, null, ex);
} catch (Exception ex) {
    Logger.getLogger(AddLaboratoryWorkCommand.class.getName()).log(Level.SEVERE, null, ex);
}

int exactCurrId = Integer.parseInt(params.get("exactCurriculumId"));
ExactGroupCurriculum egc = DAOFactory.getInstance()
        .getExactGroupCurriculumDAO()
        .findExactGroupCurriculumById(exactCurrId);

int number = Integer.parseInt(params.get("number"));
String title = params.get("title");
int credits = Integer.parseInt(params.get("credits"));

LaboratoryWork lab = new LaboratoryWork();
lab.setCredits(credits);
lab.setNumber(number);
lab.setTitle(title);
lab.setExactCurriculum(egc);
lab.setFilePath(filePath);

DAOFactory.getInstance().getLaboratoryWorkDAO().addLaboratoryWork(lab);

但没有任何反应。哪里可能是错误的?

0 个答案:

没有答案