Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i check jsp form request submit in same jsp page? (enctype="multipart/form-data")

<%
..... code to check request is submitted or not ...
%>
<form method="post" action="" name="uploadform" enctype="multipart/form-data">
  <table >  
    <tr>    
      <td>Select up to 3 files to upload</td>
    </tr>    
    <tr>    
      <td>   
        <input type="hidden" name="newFileName" value="newUploadedFileName1">
        <input type="file" name="uploadfile" >
        </td>    
    </tr>    
    <tr>    
     <td align="center">   
      <input type="submit" name="Submit" value="Upload">
      <input type="reset" name="Reset" value="Cancel">
     </td>
    </tr>
</table>
</form>

The jsp post request code to upload files will be in same page above in <% .. %> tag.

How can i add a check with if statement to check whether the Submit button is clicked or not , in other words whether a post request is sent or not.

I followed this , http://www.java2s.com/Code/Java/JSP/SubmittingCheckBoxes.htm but it did not help and that is to call a different jsp file ("formAction.jsp") not in same page .

if(request.getParameter("newFileName") != null) {

This statement always gives null value. I don't know why.

Note: it's a form with this attribute => enctype="multipart/form-data"

If i don't add any if statement then the files are uploaded for the first time , but next time if i click the reload button or refresh the page , the browser prompts me to resend the data or to reupload the previous files . I hope you have understood the problem. If there is any confusion to understand the problem please comment .

Can anyone give some hint/solution ?

like image 218
shibly Avatar asked Feb 23 '23 08:02

shibly


1 Answers

When using multipart/form-data, the request is been sent in a different encoding than the standard application/x-www-form-urlencoded encoding which the getParameter() and consorts is relying on. That's why they all return null. You need to parse the multipart/form-data request into sensible objects before being able to determine the submitted values. For that normally Apache Commons FileUpload or request.getParts() is been used. For further detail, check this answer.

Alternatively, you can also just check the request method. A normal request (link, bookmark, etc) is always GET. A form submit to upload the file is always POST.

if ("POST".equalsIgnoreCase(request.getMethod())) {
    // Form was submitted.
} else {
    // It was likely a GET request.
}

But this makes no utter sense inside a JSP. Writing raw Java code down in a JSP file is recipe for maintenance trouble. Rather submit the form to a fullworthy servlet and just implement the doPost() method. In a servlet you've all the freedom to write Java code without taking all that HTML into account.

like image 116
BalusC Avatar answered Feb 25 '23 21:02

BalusC