Error Page的使用
來源:凌群 cww整理
當JSP程式導向到錯誤訊息網頁時,JSP Engine會將例外物件放入request 物件中傳到錯誤訊息網頁,
此時你只要在錯誤訊息網頁的page編譯指令中,將isErrorPage屬性設為true,這樣就可以用預設的
exception 物件取得錯誤訊息,因為當你將 isErrorPage的屬性設為true時,jsp engine 會自動幫
你宣告一個取自於request的例外物件:
Throwable exception = (throwable)request.getAttribute(“javax.servlet.jsp.jspException”);
於是可以用exception.getMessage() 或是exception.toString()取得錯誤訊息字串,然後將它顯示於錯誤
訊息網頁上。
範例:
---------------------------------------------------------------------------------------------------------------------
<%@ page language="java" errorPage="error.jsp" %>
<html>
<body bgcolor="#FFFFFF">
<center>
-- 運算結果 --
<br>
<h1>
<%
int dividend=0;
int divisor=0;
try{
dividend = Integer.parseInt( request.getParameter( "value1" ) );
}catch( NumberFormatException nfex ){
throw new NumberFormatException( "被除數不是整數數字! " );
}
try{
divisor = Integer.parseInt( request.getParameter( "value2" ) );
}catch( NumberFormatException nfex ){
throw new NumberFormatException( "除數不是整數數字! " );
}
int result=dividend/divisor;
out.println( dividend + " / " + divisor + " = " + result );
%>
</h1>
<br><br><br>
<a href="javascript: history.back();">回上一頁</a>
</center>
</body>
</html>
============================================================
error.jsp
------------------------------------------------------------
<%@ page isErrorPage="true" contextType="text/html; charset=Big5"%>
<HTML>
<BODY>
<H1>Error page chkid</H1>
<BR>An error occured in the bean. Error Message is: <%= exception.getMessage() %><BR>
Stack Trace is : <PRE><FONT COLOR="RED"><%
java.io.CharArrayWriter cw = new java.io.CharArrayWriter();
java.io.PrintWriter pw = new java.io.PrintWriter(cw,true);
exception.printStackTrace(pw);
out.println(cw.toString());
%></FONT></PRE>
<BR></BODY>
</HTML>
转载:http://www.hosp.ncku.edu.tw/java/errpage.htm