我有一个包含其他JSP的JSP,使用如下代码:
<jsp:include page="include.jsp" />
我只是希望能够捕获异常,并在缺少include.jsp时向最终用户显示错误消息。如何检测或捕获丢失的资源条件?
答案 0 :(得分:1)
我认为JSP已经暗示了objet,其中一个是异常。
tutorialspoint 的示例:
<%@ page errorPage="ShowError.jsp" %>
<html>
<head>
<title>Error Handling Example</title>
</head>
<body>
<%
// Throw an exception to invoke the error page
int x = 1;
if (x == 1) {
throw new FileNotFoundException("Error, one file is missing!!!");
}
%>
</body>
只有您在错误页面中处理异常:
<%@ page isErrorPage="true" %>
<html>
<head>
<title>Show Error Page</title>
</head>
<body>
<h1>Opps...</h1>
<p>Sorry, an error occurred.</p>
<p>Here is the exception stack trace: </p>
<pre>
<% exception.printStackTrace(response.getWriter()); %>
</pre>
</body>
</html>
答案 1 :(得分:0)
在原始JSP中
<%@ page errorPage="errorPage.jsp" %>
<html>
<head>
<title>JSP exception handling</title>
</head>
<body>
<jsp:include page="include.jsp" />
</body>
</html>
然后,在您的errorPage.jsp
中<%@ page isErrorPage="true" %>
<html>
<head>
<title>Display the Exception Message</title>
</head>
<body>
<h2>errorPage.jsp</h2>
<i>An exception has occurred. Please fix the errors. Below is the error message:</i>
<b><%= exception %></b>
</body>
</html>
积分 :从本教程中摘录的示例:http://beginnersbook.com/2013/11/jsp-exception-handling/
答案 2 :(得分:0)
您应该使用java.io.File
检查文件是否丢失。
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@page import="java.io.*"%>
<%@page import="java.io.File.*"%>
<%
String filename = "kpisrc/getNowTime2.jsp";
File f = new File(filename);
if(f.exists()){
%>
<jsp:include page="<%=filename%>" ></jsp:include>
<%
}else{
out.print(filename + " not found.");
}
%>
或者检查文件是否存在的另一种方法
if(null == application.getResource(filename))
答案 3 :(得分:0)
通过尝试/捕获?
<%
try {
%>
<jsp:include page="<%=filename%>" ></jsp:include>
<%
} catch(Exception e) {
%>
the file, <%=filename%>, is missing.
<%
}
%>