jsp页面的例外处理

          在这篇文章中,我将向你讲解一个jsp页面例外(Exceptions)是怎样抛出(Throw)并且怎样捕捉这些例外,以便使你在jsp设计中能得到更有利的信息.
          首先,什么是Exceptions?众所周知Exceptions就是一个异常事件,它可能出现在程序的任何地方,比如:你试图连接一个数据库,但是这个数据库已经关闭,这时就产生一个例外.
        如何捕捉(throw)一个例外啦?我们可以用下面的表达式:
<%
try {
  // Code which can throw can exception
} catch(Exception e) {
             // Exception handler code here
}
%>
当然,还有另外的一种有用的方法:就是指定专用的例外处理页面,当例外发生时便由它来处理.这就是我下面要讲述的.
    建立三个页面:1.Form.html(简单的年龄输入筐)代码如下:

<html>
<head>
	<style>
	body, input { font-family:Tahoma; font-size:8pt; }
	</style>
</head>
<body>

<!-- HTML Form -->
<form action="FormHandler.jsp" method="post">
	Enter your age ( in years ) : 
	<input type="text" name="age" /> 
	<input type="submit" value="Submit" />
</form>

</body>
</html>
2:FormHandler.jsp()(处理由Form.html传来的age)代码如下:





<%@ page errorPage="ExceptionHandler.jsp" %>
<html>
<head>
	<style>
	body, p { font-family:Tahoma; font-size:10pt; }
	</style>
</head>
<body>

<%-- Form Handler Code --%>
<%
	int age;

		age = Integer.parseInt(request.getParameter("age"));
%>

<%-- Displaying User Age --%>
<p>Your age is : <%= age %> years.</p>

<p><a href="Form.html">Back</a>.</p>

</body>
</html>

请注意:(1)<%@ page errorPage="ExceptionHandler.jsp" %>是指明了一个例外处理页面,它必须在jsp的第一行.(2)

<%
	int age;

		age = Integer.parseInt(request.getParameter("age"));
%>是取得age(String类)并转化为int(类).<p>Your age is : <%= age %> years.</p>
是输出你刚才输入的age,现在例外就可能发生了,如果 你输入的不是数字,比如:zsa;这时String能转化成int吗?
3.ExceptionHandler.jsp(处理例外)代码如下:
<%@ page isErrorPage="true" import="java.io.*" %>
<html>
<head>
	<title>Exceptional Even Occurred!</title>
	<style>
	body, p { font-family:Tahoma; font-size:10pt; padding-left:30; }
	pre { font-size:8pt; }
	</style>
</head>
<body>

<%-- Exception Handler --%>
<font color="red">
<%= exception.toString() %><br>
</font>

<%
out.println("<!--");
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
exception.printStackTrace(pw);
out.print(sw);
sw.close();
pw.close();
out.println("-->");
%>

</body>
</html>
注意:<%@ page isErrorPage="true" %>表明:当jsp宣称了一个errorPage时,应该声明isErrorPage="true;
<%
out.println("<!--");
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
exception.printStackTrace(pw);
out.print(sw);
sw.close();
pw.close();
out.println("-->");
%>运用了PrintWriter和StringWrighter类,所以你不得不声明:import java.io.* 在你jsp程序中;即:
<%@ page isErrorPage="true" import="java.io.*" %>
好了:开始演示:在ie中输入http://localhost:8080/myapp/Form.html 回车!当然你先要启动tomcat!

看见了吗?在输入筐中入任何一个数字:24等:结果是:Your age is : 24 years
再试一下:输入:zsa.是什么结果啦??
java.lang.NumberFormatException: For input string: "zsa";
明白了吧!!!!
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值