Response.sendRedirect - check redirection up

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

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

Is it possible to check if google.com is running and then redirect (or write 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 
}%>

This is just a JSP page, I don't have libraires available (e.g. ApacheCommons for http GET methods).

+3
source share
3 answers

JSP JSTL ( jstl-1.2.jar /WEB-INF/lib) <c:import> <c:catch> . <c:import> IOException (FileNotFoundException), . <c:catch> Throwable . <c:choose> ( <c:if>) .

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

var="ignore" , JSP.


, JSP . HttpServlet Filter JSP, , . JSP - . a HttpServlet :

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

, , , , , .

, , HTTP 302 , , .

0

IMHO this is not a good idea. You can write Java code that tries to open a connection to port 80 on www.google.com and check if you have a 200 response code. But keep in mind that this will slow down the rendering time of your page!

0
source

Source: https://habr.com/ru/post/1747811/


All Articles