In pure JSP, I would grab JSTL (just put jstl-1.2.jar in /WEB-INF/lib
) <c:import>
and <c:catch>
for this. The <c:import>
will throw an IOException
(FileNotFoundException
) when the other side cannot be reached. With the <c:catch>
you can catch any Throwable
into a variable. With the <c:choose>
(or <c:if>
) you can handle the outcome accordingly.
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<c:set var="url" value="http://google.com" />
<c:catch var="e">
<c:import url="${url}" var="ignore"></c:import>
</c:catch>
<c:choose>
<c:when test="${not empty e}">
<p>Site doesn't exist
</c:when>
<c:otherwise>
<c:redirect url="${url}" />
</c:otherwise>
</c:choose>
The var="ignore"
is mandatory because it would otherwise include all page contents in the JSP.
That said, I wouldn't use JSP for this. Prefer a HttpServlet
or Filter
above JSP when you want to control, preprocess or postprocess requests. JSP is a view technology and should be used as is. In a HttpServlet
I would do more like this:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String url = "http://google.com";
try {
new URL(url).openStream(); // Will throw UnknownHostException or FileNotFoundException
response.sendRedirect(url);
} catch (IOException e) {
throw new ServletException("URL " + url + " does not exist", e); // Handle whatever you want. Forward to JSP?
}
}