user1965119
user1965119

Reputation: 1

How to catch missing JSP file Exception

I have a JSP that includes other JSPs using code like this:

<jsp:include page="include.jsp" />

I simply want to be able catch the exception and show the end user an error message if include.jsp is missing. How can I detect or catch the missing resource condition?

Upvotes: 0

Views: 1585

Answers (4)

waffledonkey
waffledonkey

Reputation: 101

by using try/catch?

<%
    try {
%>
        <jsp:include page="<%=filename%>" ></jsp:include>
<% 
    } catch(Exception e) {
%>
        the file, <%=filename%>, is missing.
<%
    } 
%>

Upvotes: 0

Wong Ayeah
Wong Ayeah

Reputation: 1

You should use java.io.File to check whether the file is missing.

<%@ 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.");
}

%>

Or another way to check file exists if(null == application.getResource(filename))

Upvotes: 0

blurfus
blurfus

Reputation: 14031

In your original JSP

<%@ page errorPage="errorPage.jsp" %>
<html>
<head>
  <title>JSP exception handling</title>
</head>
<body>
    <jsp:include page="include.jsp" />
</body>
</html>

Then, in your 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>

Credits: Examples extracted from this tutorial: http://beginnersbook.com/2013/11/jsp-exception-handling/

Upvotes: 0

Ovatsug
Ovatsug

Reputation: 23

I think JSP has implicits objetcs, one of them is Exception.

Example of 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>

And only you have handle the exception in the error page:

<%@ 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>

Upvotes: 1

Related Questions