2016-10-02 50 views
1

我試圖從txt文件中讀取並將其顯示到JSP文件中。默認的構造函數無法處理異常類型由隱式超級構造函數拋出的異常

Bean類從FileReaderz類獲取BufferedReader。 我創建JSP一個Beanx對象,但是這是我卡住

public class Beanx { 
     public OuterBlock[] outer=new OuterBlock[100]; 
     public InnerBlock[] inner=new InnerBlock[100]; 

     /*public List<String> token1 = new ArrayList<String>(); 
     public List<String> token2 = new ArrayList<String>();*/ 
     //String[] token1; 
     //String[] token2; 

     public void callFileReaderz()throws Exception{ 
      FileReaderz fr=new FileReaderz(); 
      BufferedReader br1=FileReaderz.br; 
      String[] token; 
      int i=0,j=0; 

      String line; 
      while((line=br1.readLine())!=null){ 
       //System.out.println(line); 
       token=line.split("#"); 
       //List<String> tokenList=Arrays.asList(token); 
       if(token.length==5){ 
        OuterBlock outerObj=new OuterBlock(token[0],Integer.parseInt(token[1]),Integer.parseInt(token[2]), 
          Float.parseFloat(token[3]),Float.parseFloat(token[4])); 
        this.outer[i++]=outerObj; 
        //System.out.println(token[0]); 

       } 
       else{ 
        InnerBlock innerObj = new InnerBlock(token[0],token[1],Integer.parseInt(token[2]), 
          Integer.parseInt(token[3]),Float.parseFloat(token[4]),Float.parseFloat(token[5])); 
        this.inner[j++]=innerObj; 

       } 
      } 
      br1.close(); 

     } 

     public Beanx() throws Exception{ 
      this.callFileReaderz(); 
     } 
    } 


    public class FileReaderz { 
     public static BufferedReader br; 

     public static void main (String[] args)throws Exception { 
      // TODO Auto-generated method stub 
      //public FileReaderz() throws FileNotFoundException{ 
      br=new BufferedReader(new FileReader("database1.txt")); 

    //System.out.println(br.readLine()); 
    } 

} 

當我嘗試這在JSP頁面中,

我得到的錯誤:

org.apache.jasper.JasperException: Unable to compile class for JSP: 

An error occurred at line: 15 in the jsp file: /dashBoard.jsp 
Default constructor cannot handle exception type Exception thrown by implicit super constructor. Must define an explicit constructor 
12: </head> 
13: 
14: <body> 
15: <%! Beanx bean=new Beanx(); %> 
16: <div class="table-title"> 
17: <h3>Projects In Repository</h3> 
18: </div> 
+0

錯誤消息已足夠清楚。你對此不瞭解什麼? – Raedwald

回答

1

這是因爲Beanx類構造函數會拋出Exception,並且您正在聲明標記中創建Beanx對象而不處理異常。

要解決此問題只是null如下初始化Beanx在聲明標籤:

<%! Beanx bean =null; %> 

,每當你需要使用這個bean在小腳本標籤使用下面的代碼:

<% 
    try{ 

     bean=new Beanx(); 

     }catch(Exception e){ 
     //To do something 
     } 
%> 

這與下面的java代碼相同:

class Main extends HttpServlet{ 

Beanx bean =null; 

protected void doGet(HttpServletRequest request, HttpServletResponse response){ 
    try{ 

     bean=new Beanx(); 

     }catch(Exception e){ 
     //To do something 
     } 
} 
}