我正在使用Tomcat,希望在访问未被Servlet处理的网址时,执行其他操作而非展示默认错误页面。
type Status report
message /test
description The requested resource is not available.
我应该在哪里处理这个问题?
先行感谢。
type Status report
message /test
description The requested resource is not available.
我应该在哪里处理这个问题?
先行感谢。
在 web.xml 文件中定义错误页面:
<error-page>
<error-code>404</error-code>
<location>/path/to/your/page.html</location>
</error-page>
更新
您可以按其HTTP状态(404、500等)或定义完全限定的异常名称(java.lang.Exception、java.io.FileNotFoundException等)来定义错误页面。如果您使用Servlet 3.x,甚至可以忽略error-code/error-classname部分以定义默认错误页面。
这是一个最小的web.xml
文件,您可以将其放在webapps文件夹中(如果您不想全局更改404页面)。这样可以让您将所有请求重定向到一个新的文件夹。
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0"
metadata-complete="true">
<error-page>
<error-code>404</error-code>
<location>/redirect.jsp</location>
</error-page>
</web-app>
web.xml
必须放在.../webapps/YourFolder/WEB-INF/web.xml
中。redirect.jsp
中,你可以放置如下内容:<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en" dir="ltr">
<head>
<title>Moved</title>
</head>
<%
// get the requested URI
String requestedLocation = request.getRequestURI();
// rewrite to new location
String newLocation = requestedLocation.replaceAll("^/Old", "/New");
// 301 - permanent redirect
response.setStatus(response.SC_MOVED_PERMANENTLY);
response.setHeader("Location", newLocation);
%>
<body>
→ <a href="<%=newLocation%>"><%=newLocation%></a>
</body>
</html>
自Tomcat 9以来,有不同的错误处理配置。
您需要:
<Valve className="org.apache.catalina.valves.ErrorReportValve" errorCode.404="webapps/ROOT/error_page.html" errorCode.0="webapps/ROOT/error_page.html" showReport="false" showServerInfo="false" />