例 3.6 页面出现异常的处理。
创建 example3_6.jsp 页面,使用 page 指令
的 errorPage 属性指定页面出现异常时所转向的页面。该程序执行的是除法运
算 , 如 果 除 数 为 0 , 将 会 拋 出 一 个 数 学 运 算 异 常 , 从 errorPage="
example3_6_error.jsp" 可以看出,程序指定 example3_6_error.jsp 为其处理
异常。再创建 example3_6_error.jsp 页面,使用 page 指令的 isErrorPage 属
性指定为出错页面,此页面可以使用 exception 异常对象处理错误信息。
example3_6.jsp 具体代码如下:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" errorPage="example3_6_error.jsp"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>example3_6.jsp</title>
</head>
<body>
<%
int x1=5;
int x2=0;
int x3=x1/x2;
out .print (x3);
%>
</body>
</html>
example3_6_error.jsp 具体代码如下:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" isErrorPage="true"%>
<!DOCTYPE html >
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>example3_6error.jsp</title>
</head>
<body>
出现错误,错误如下:<br/>
<hr>
<%=exception.getMessage() %>
</body>
</html>
例 3.7
编写 example3_7.jsp 页面,页面显示“请输入两个整数,单击提交
按钮求这两个整数的平方差”。再编写一个 example3_7_input.jsp 页面,其中显
示表单,输入两个整数后,单击提交按钮后可以显示出两数的平方差,效果如下
图所示。要求在 example3_7.jsp 页面包含 example3_7_input.jsp。
example3_7.jsp 具体代码如下:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html >
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>example3_7.jsp</title>
</head>
<body>
<p>请输入两个整数,单击提交按钮求这两个数的平方差</p>
<%@ include file="example3_7input.jsp" %>
</body>
</html>
example3_7_input.jsp 具体代码如下:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html >
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>example3_7_inpute.jsp</title>
</head>
<body>
<form action="" method="post">
整数1: <input type="text" name="n1"/>
<br/><br/>
整数2: <input type="text" name="n2"/>
<br/><br/><input type="submit" value="提交"/>
</form>
<%
String n1=request.getParameter("n1");
String n2=request.getParameter("n2");
if(n1!=null&n2!=null){
int a,b;
try{
a=Integer.parseInt(n1);
b=Integer.parseInt(n2);
%>
<p>你输入的两个整数的平方差是:<%=a*a-b*b %></p>
<%
}
catch(Exception e){
out.print("请输入两个整数!");
}
}
%>
</body>
</html>