我只想从 JSP 重定向到另一个页面...
<% response.sendRedirect("http://www.google.com/"); %>
我可以检查 google.com 是否已启动,然后重定向(或写一条消息)...
类似的东西:
<% if(ping("www.google.com")) {
response.sendRedirect("http://www.google.com/");
} else {
// write a message
}%>
或者
<% try {
response.sendRedirect("http://www.google.com/");
} catch(SomeException e) {
// write a message
}%>
它只是一个 JSP 页面,我没有任何可用的库(比如用于 http GET 方法的 ApacheCommons)。
请您参考如下方法:
在纯 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 是一种 View 技术,应该按原样使用。在 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?
}
}