views:

181

answers:

3

From JSP I just want a redirect to another page...

<% response.sendRedirect("http://www.google.com/"); %>

Can I check if google.com is up and then redirect (or write a msg else)...

Something like that:

<% if(ping("www.google.com")) {
     response.sendRedirect("http://www.google.com/");
} else {
     // write a message 
}%>

Or

<% try {
     response.sendRedirect("http://www.google.com/");
} catch(SomeException e) {
     // write a message 
}%>

It is just an JSP page, I don't have any libraires available (like ApacheCommons for http GET methods).

A: 

You can try to check connectivity form your server to the target like in your first example, but it will make the thread wait for this which is probably not desirable.

The second won't really do what you think it does - it just sends an HTTP 302 to the client, and the client may or may not follow the redirect but in any case you will not get an exception from it.

ob1
You might consider verifying in a separate thread or with Quartz timer task and checking if the last time the thread checked the site was available.
Peter Tillemans
Yes, that would be helpful towards the original goal here
ob1
A: 

It's IMHO not a good idea to do so. You could write java code that tries to open a connection to port 80 at www.google.com and check if you get a 200 response code. But be aware that this will slow down your page rendering time!

Patrick Cornelissen
A: 

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?
    }
}
BalusC