2014-04-09 53 views
0

我正在處理我有的任務。這是相當直接的。一個包含單個輸入的HTML表單被提交給一個Servlet,該Servlet獲取參數,根據參數創建一條消息,將消息作爲屬性添加到請求中,並使用requestdispatcher轉發給jsp以顯示消息。處理servlet中的異常

我有一個要求,如果參數丟失,我需要顯示一個錯誤頁面。問題在於我無法顯式檢查null,或者使用try/catch塊。我的猜測是,目標是在web.xml頁面中定義一個錯誤頁面來處理某種類型的錯誤,但問題是,如果我無法檢查請求參數是否爲空,或者使用try/catch ,我怎麼知道我是否需要拋出異常?有任何想法嗎?

+0

閱讀有關servlet異常處理程序以及如何將異常映射到這些處理程序的信息。 –

+0

從我讀過的內容來看,通常的做法是讓servlet拋出某種異常,並允許容器處理它。問題是,如果我不能檢查null,或者使用try/catch,我不知道是否/何時拋出異常。 – user1154644

+0

只需將該異常添加到處理請求的方法的簽名即可。 –

回答

0

在web.xml中,可以像這樣指定一個錯誤頁面。
讓我們假設你想趕上HTTP400,500種異常:

<error-page> 
    <error-code>400</error-code> 
    <location>/errorpage.html</location> 
</error-page> 
<error-page> 
    <error-code>500</error-code> 
    <location>/errorpage.html</location> 
</error-page> 

(由Arjit的建議)

<error-page> 
    <exception-type>java.lang.Exception</exception-type> 
    <location>/errorpage.html</location> 
</error-page> 

然後把它放在一起,由DeveloperWJK的建議,在servlet :

public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException, NullPointerException 
{ 
     String param = request.getParameter("param"); 
     if(param.equals("x")) 
     { 
      response.sendRedirect("x.jsp"); 
      return; 
     } 
} 
+0

我想它會拋出一個'500'爲空的錯誤 –

0

如果您打算根據參數創建一條消息,那麼如果您無法檢查標準參數如何實現此目標有點困難ameters值(例如null)。想必你叫......

HttpServletRequest.getParameter()

如果參數丟失返回參數值或空。

0

web.xml,你也可以提到異常。

<error-page> 
    <exception-type>java.lang.Exception</exception-type> 
    <location>/error.jsp</location> 
</error-page> 

或者您可以從此鏈接獲取幫助以創建新的servlet來處理錯誤。 Servlet Exception Handling

+0

問題是關於一個Servlet而不是一個JSP。 – developerwjk

0

通常檢查null你會怎麼做:

 String param = request.getParameter("param"); 
     if(param!=null) 

如果他們不希望你這樣做,這樣做,可能他們希望你使用點操作引起NullPointerExpection

public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException, NullPointerException 
{ 
     String param = request.getParameter("param"); 
     if(param.equals("x")) 
     { 
      //if param was null, simply using 
      //the DOT operator on param would throw 
      // the NullPointerExpection 
      response.sendRedirect("x.jsp"); 
      return; 
     } 
    } 

爲了避免明確檢查空和避免你可以做NullPointerExpection:

if("x".equals(param))