有没有一种简单的方法来处理JSP文件中的404错误?

时间:2012-09-15 18:41:24

标签: java jsp java-ee

我不想每次都使用:

if(!new File(file).exists()){
    //createFile /doc/a.txt ...
}
request.getRequestDispatcher("/doc/a.txt").forward(request, response);

我想知道如何实现以下代码:

try{
    request.getRequestDispatcher("/doc/a.txt").forward(request, response);
}catch(404 error){
    //createFile /doc/a.txt ...
}

如何在此页面中处理404错误?

非常感谢任何建议。

2 个答案:

答案 0 :(得分:0)

最好通过web.xml中的错误部分来处理:

<error-page>
    <error-code>404</error-code>
    <location>/ErrorPage.jsp</location>
</error-page> 

答案 1 :(得分:0)

为什么这不适合你:

try{
    request.getRequestDispatcher("/doc/a.txt").forward(request, response);
}catch(Exception error){
    //createFile /doc/a.txt ...
}