1

For simplicity purposes, I have a jsp file with a small form that contains 2 select options, a file upload option, and a submit button. A servlet receives the values, processes them (i.e. puts the file into a database), and then displays a message via a request attribute and a redirect back to the original jsp page.

My problem is that when the user tries to upload another file from that same jsp page, the servlet is receiving the select values that were selected from the previous submit, instead of the new attempt to submit. How can the same user upload another file with different values for the select options, after the servlet has already redirected back to the jsp?

Similarly, how can the success message that was printed from the first submit be cleared until another successful upload happens? Currently, the success message stays one the page even after the user has begun to choose new values to submit.

Here is the relevant code:

JSP file

<body >

<h3 style="color:red">${msg4}</h3>

<form id="uploadForm" method="post" action="UploadServlet"enctype="multipart/form-data">
<br />

<% UserBean currentUser = (UserBean)(session.getAttribute"currentSessionUser"));%>

Course Number:
 <select name="courseNo">
   <option value="CS1">CS1</option>
   <option value="CS2">CS2</option>
 </select> 
<br />
Assignment Number:
 <select name="hwNo" id="hwNo" >
   <option value="1">1</option>
   <option value="2">2</option>
   <option value="3">3</option>
 </select> 
<br />
Assignment (must be a zip file): <input type="file" name="dataFile"     id="fileChooser" /><br />

<br /> <input type="submit" value="Upload" />
</form>

<h3 style="color:red">${msg2}</h3>

</body>

Relevant Servlet Code

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        HttpSession session = request.getSession(true);
        UserBean currentUser = (UserBean)(session.getAttribute("currentSessionUser"));
        String uName = currentUser.getUsername();


        if (!ServletFileUpload.isMultipartContent(request))
        {return;}


        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(THRESHOLD_SIZE);
        factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setFileSizeMax(MAX_FILE_SIZE);
        upload.setSizeMax(REQUEST_SIZE);


        try 
        { 
            List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
            for (FileItem item : items) 
            {
                if (item.isFormField()) 
                {
                    String fieldname = item.getFieldName();

                    if(fieldname.equals("courseNo"))
                        courseNo = item.getString();
                    if(fieldname.equals("hwNo"))
                    {
                        hwNo = item.getString();
                        homeworkNo = Integer.parseInt(hwNo);    
                    }   

                Boolean exists = checkIfHWNoExists(homeworkNo, uName);
                if(exists)
                {
                    request.setAttribute("msg4", "You've already made a submission for " +
                                        "assignment number " + homeworkNo +"." +
                                        "<br />If you need to change your submission, " +
                                        "please contact your teacher.");
                    request.getRequestDispatcher("/upload.jsp").forward(request, response);
                    return;
                }

            }

            if (!item.isFormField())
            {
                (item.getName()).getName();
                File storeFile = new File(item.getName());
                String fileName = storeFile.getName();
                if(!fileName.endsWith(".zip"))
                {
                    request.setAttribute("msg", "Must be a zip file!  Try again!");
                    request.getRequestDispatcher("/upload.jsp").forward(request, response);
                    return;
                }


                else
                {
                    String mimeType = new MimetypesFileTypeMap().getContentType(storeFile);
                                                            //for putting file into database
                    putFileIntoDB(uName, homeworkNo, fileName, mimeType, storeFile);


                    request.setAttribute("msg2", "File uploaded successfully!");
                    request.getRequestDispatcher("/upload.jsp").forward(request, response);
                }
            }
        }


            //request.setAttribute("message", "Upload has been done successfully!");

   }
    catch (Exception ex)
    {
        request.setAttribute("message", "There was an error: " + ex.getMessage());
    }

    ("/message.jsp").forward(request, response);


        }
Lani1234
  • 522
  • 5
  • 12
  • 21
  • Actually, to be more specific, the servlet is capturing the new "Course No" correctly, but not changing the value of "Homework no" to the new selection after subsequent submits...I can't see why that's happening. – Lani1234 Feb 19 '13 at 16:07
  • 1
    By looking at your code, it loos like you have declared the `courseNo`, `hwNo` and `homeworkNo` variables as servlet attributes. You should move those variables definitions inside your `doPost` function in order to avoid these kind of problems. Please refer to [How do servlets work? Instantiation, session variables and multithreading](http://stackoverflow.com/q/3106452/1065197) – Luiggi Mendoza Feb 19 '13 at 21:16
  • I apologize, but I found the problem. On the first loop through the List of FileItems, only the courseNo is being assigned. Inside that loop, it is also calling checkIfHWNoExists, prior to the new homeworkNo value being assigned. So on subsequent submissions, it is never reaching the part of the loop where homeworkNo is assigned the new value, and only checking against the old value. I will post the corrected code later, in case it can be of help to someone else. – Lani1234 Feb 19 '13 at 21:30
  • Please post your corrected code as an answer and do not edit your question. – Luiggi Mendoza Feb 19 '13 at 21:30
  • Thank you Luiggi Mendoza. I will move those declarations into the doPost in order to avoid problems. I hadn't thought of that. I am new to servlets but happy to be learning all about them, so I appreciate the link. I will read through it. And yes, I will post the corrected code as an answer - also a good suggestion. Thank you for taking a look. – Lani1234 Feb 19 '13 at 21:32

1 Answers1

0

The problem was in the loop in the servlet. Here is the corrected doPost method with the loop removed completely, as it was not necessary.

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
    String courseNo;
    int homeworkNo;

    HttpSession session = request.getSession(true);
    UserBean currentUser = (UserBean)(session.getAttribute("currentSessionUser"));
    String uName = currentUser.getUsername();

    if (!ServletFileUpload.isMultipartContent(request))
    {return;}


    try 
    { 
        List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);

        courseNo = items.get(0).getString();
        homeworkNo = Integer.parseInt(items.get(1).getString());    
        if(checkIfHWNoExists(courseNo, homeworkNo, uName))
        {
          request.setAttribute("msg4", "You've already made a submission for Course Number " + courseNo + ", "+
                                    "Assignment number " + homeworkNo +"." +
                                    "<br />If you need to change your submission, " +
                                    "please contact your teacher.");
                request.getRequestDispatcher("/upload.jsp").forward(request, response);
                return;
            }

         else//ok to add new HW, it doesn't exist
         {
          File storeFile = new File(items.get(2).getName());
          String fileName = storeFile.getName();

          if(!fileName.endsWith(".zip"))
          {
              request.setAttribute("msg", "Must be a zip file!  Try again!");
              request.getRequestDispatcher("/upload.jsp").forward(request, response);
          return;
          }

            else
            {  
                String mimeType = new MimetypesFileTypeMap().getContentType(storeFile); //for putting file into database
                      putFileIntoDB(uName, courseNo, homeworkNo, fileName, mimeType, storeFile);

              request.setAttribute("msg2", "File uploaded successfully!");
              request.getRequestDispatcher("/upload.jsp").forward(request, response);
            }
         }

    }//try
    catch (Exception ex)
     {
       request.setAttribute("msg", "There was an error: " + ex.getMessage());
       request.getRequestDispatcher("/upload.jsp").forward(request, response);
      }

}
Lani1234
  • 522
  • 5
  • 12
  • 21