JSP/Servlet 无法从文本区域获取文本

JSP/Servlet can't get text from textarea

我正在尝试将一张带有说明的照片上传到数据库。基本上我已经成功上传了照片,但是描述(评论)总是设置为空。

index.jsp 包含带有文件输入和文本区域的表单

<textarea class="form-control" rows="2" id="comment" name="comment" placeholder="Write something"></textarea>

Servlet 代码:

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    String comment = request.getParameter("comment");

    if(ServletFileUpload.isMultipartContent(request)){
        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));
                    // till now, the photo is being saved in a folder
                    // method addPhoto uploads this photo in database
                    // this method works OK
                    addPhoto((int) request.getSession().getAttribute("id"), UPLOAD_DIRECTORY + File.separator + name , comment);
                }
            }

           request.setAttribute("message", "File Uploaded Successfully");
        } catch (Exception ex) {
           request.setAttribute("message", "File Upload Failed due to " + ex);
        }          
    }
    request.getRequestDispatcher("/index.jsp").forward(request, response);
}

如果有人能帮助我,我该如何在数据库中设置照片的描述?

当请求编码为"multipart/form-data"时,需要解析请求后获取参数。在你的代码中,你可以尝试

for(FileItem item : multiparts){
 if(!item.isFormField()){
   // the logic you already have now
 } else {
   if ("comment".equals(item.getFieldName())) {
        String comment = item.getString();
    // Whatever you have to do with the comment
   }
 }
}