tags:

views:

69

answers:

2

Hi I am new to JSP and i am trying to write the below code...

<%@ page import="java.io.*" %>
<%@ page import="com.wipro.assignment2.exceptions.UploadFileNotFoundException" %>
<%
    String requestPath=request.getParameter("file1");
        System.out.println("I am printing before SUBMIT button click");
    if(requestPath!=null)
    {
     File f=new File(requestPath.trim()); 
     System.out.println("Path given to upload : "+requestPath);
     if(!f.exists())
     {
     System.out.println("one");   
      try
      {
       throw new UploadFileNotFoundException("The file trying to upload is not presnt in its path !!!");
      }
      catch(UploadFileNotFoundException filenotfound)
      {
       throw filenotfound;
      }
     }
    }
%>

<html>
<body>
<form  name="form1" method="post"  enctype="multipart/form-data">
    <table align="right">
     <tr>
      <td><A href="index.html">HOME</A></td>
     </tr>
    </table>

    </table>
    <table>
     <tr>
      <td>Select File  </td>
      <td> <input type="file" name="file1"> </td>
     <tr>
      <td><input type="submit" value="Upload"></td>
     </tr>
    </table>

</form>
</body>
</html>

Here in the above code once this JSP page is loaded, before the submit button is being clicked, JSP starts running and if i press the submit button, the request is not passed to the above JSP... Please gimme the idea how it really works..

Thanks in advance

+2  A: 

I think the problem is that you haven't told your <form> where to post to. Form's have an attribute named action that indicates which URL the form data should be sent to. Try changing your form element to post to your JSP

<form  action="/path/to/your.jsp" name="form1" method="post"  enctype="multipart/form-data">

Also, it's generally considered a bad practice to include scriptlet (Java) code in JSPs. Try to find some tag libraries (e.g. JSTL) that you can use instead. In particular the following code is fairly pointless:

try
{
    throw new UploadFileNotFoundException("The file trying to upload is not presnt in its path !!!");
}
catch(UploadFileNotFoundException filenotfound)
{
    throw filenotfound;
}

Here, you're throwing an exception, catching it, and re-throwing it. Which is identical to just throwing it.

throw new UploadFileNotFoundException("The file trying to upload is not presnt in its path !!!");

Unless you want the user to be shown an error page (the default behaviour when an uncaught exception is thrown) it would be better to return some HTML describing the problem than throwing an exception.

Don
Thanks Don, I will try it
i2ijeya
I new to JSP Don.. So could you please say why we should use TAG libraries.
i2ijeya
A: 

Hi, You may use

if (request.getContentLength() > 0) {
  // .. bla bla
}

and additional information: You may use apache commons fileuplad package.

http://commons.apache.org/fileupload/

Fırat KÜÇÜK