从理论上讲,你应该能够修改默认的Tomcat Web应用程序的web.xml中,但根据this,不为Tomcat 7
工作
您的其他选择是扩展标准ErrorReportValve
。我已经从现有ErrorReportValve
代码“借”非常宽松:
public class Custom404Valve extends ErrorReportValve{
public void invoke(Request request, Response response) throws IOException, ServletException {
if(request.getStatusCode() != 404){
super.invoke();
return;
}
// Perform the request
getNext().invoke(request, response);
if (response.isCommitted()) {
if (response.setErrorReported()) {
try {
response.flushBuffer();
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
}
response.getCoyoteResponse().action(ActionCode.CLOSE_NOW, null);
}
return;
}
response.setSuspended(false);
//this is where your code really matters
//everything prior are just precautions I lifted
//from the stock valve.
try {
response.setContentType("text/html");
response.setCharacterEncoding("utf-8");
String theErrorPage = loadErrorPage();
Writer writer = response.getReporter();
writer.write(theErrorPage);
response.finishResponse();
} catch (Throwable tt) {
ExceptionUtils.handleThrowable(tt);
}
if (request.isAsyncStarted()) {
request.getAsyncContext().complete();
}
}
protected String loadErrorPage() {
BufferedReader reader = null;
StringBuilder errorMessage = new StringBuilder();
try{
File file = new File("YourErrorPage.html");
reader = new BufferedReader(new FileReader(file));
while (reader.ready()) {
errorMessage.append(reader.readLine());
}
}catch (IOException e){
e.printStackTrace();
}finally{
try{
reader.close();
}catch (IOException e) {
e.printStackTrace();
}
}
return errorMessage.toString();
}
}
你现在需要做的是配置自定义阀:
<Host name="localhost" appBase="webapps" unpackWARs="true" autoDeploy="true" xmlValidation="false" xmlNamespaceAware="false">
<Valve className="com.foo.bar.Custom404Valve"/>
</Host>
@Magnilex感谢编辑我的问题。你能帮我解决吗? – 2015-02-23 09:42:28
对不起,我没有时间。顺便说一下,你真的使用JEE堆栈吗?为此,通常使用像JBoss这样的应用服务器。如果没有,那么你已经用错误的标签标记了问题。 – Magnilex 2015-02-23 09:46:16
@Magnilex我正在使用Web服务器(Apache Tomcat 7.0),而不是任何应用程序服务器。 – 2015-02-23 09:57:46