2009-09-15 38 views
1

我是新來的JSP,我試圖寫下面的代碼:簡單的JSP應用

<%@ 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> 

在這裏,一旦這個JSP頁面加載上面的代碼,被點擊提交按鈕之前,JSP開始運行,如果我按下提交按鈕,請求不會傳遞給上面的JSP。請告訴我它是如何工作的。

回答

2

我認爲問題在於你還沒有告訴你<form>要發佈到哪裏。表單有一個名爲action的屬性,用於指示表單數據應該發送到哪個URL。嘗試更改表單元素以發佈到您的JSP

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

此外,在JSP中包含scriptlet(Java)代碼通常被認爲是不好的做法。嘗試找到一些您可以使用的標記庫(例如JSTL)。特別是下面的代碼是毫無意義的:

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

在這裏,你拋出一個異常,捕捉它,並重新拋出它。這與扔它相同。

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

除非你希望用戶顯示一個錯誤頁面(當未捕獲的異常被拋出的默認行爲),這將是更好的返回一些HTML描述不是拋出異常的問題。

+0

謝謝唐,我會嘗試 – i2ijeya 2009-09-15 14:59:59

+0

我剛接觸JSP唐..所以,請你說我們爲什麼要使用標籤庫。 – i2ijeya 2009-09-15 15:33:24