Java 将 404 错误页面重定向到 Tomcat 中我的 Spring MVC webapp 的自定义页面

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18780257/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 10:59:31  来源:igfitidea点击:

Redirecting a 404 error page to a custom page of my Spring MVC webapp in Tomcat

javaspring-mvctomcat7

提问by Hitesh

I am working with tomcat 7 and I've built and deployed a Spring MVC webapp in tomcat 7 and it's working perfectly fine. What I want is that, whenever a 404 error occurs on my server, it should be redirected to a custom page which I have built in my webapp. I have configured my webapp as a default webapp in tomcat.

我正在使用 tomcat 7,我已经在 tomcat 7 中构建并部署了一个 Spring MVC webapp,它工作得非常好。我想要的是,每当我的服务器上发生 404 错误时,它应该被重定向到我在我的 web 应用程序中构建的自定义页面。我已将我的 webapp 配置为 tomcat 中的默认 webapp。

I have tried doing this:

我试过这样做:

<error-page>
    <error-code>404</error-code>
    <location>/WEB-INF/templates/error/error.html</location>
</error-page>

But all in vain.

但一切都是徒劳的。

Glad if someone can help me out in this.

很高兴有人能帮我解决这个问题。

回答by Suresh Atta

Since you are already working in WEB-INF(web.xml) folder,You need not to mention WEB-INF.

由于您已经在WEB-INF(web.xml) 文件夹中工作,因此您无需提及WEB-INF.

<error-page> <error-code>404</error-code> 
        <location>/templates/error/error.html</location>
                                                 </error-page>

Check this tutorialalso.

也检查本教程

回答by andvicoso

You can do something like this:

你可以这样做:

<error-page>
    <error-code>404</error-code> 
    <location>error404</location>
</error-page>

And then:

进而:

@Controller
public class ErrorController {

    @RequestMapping("/error404")
    protected String error404() {
        return "/templates/error/error.html";
    }
}

回答by Yassine.b

Go to your WEB-INF folder > views.

转到您的WEB-INF 文件夹 > views

Create a page for example : error_404.jsp.

创建一个页面,例如:error_404.jsp。

Now you have to create a controller.

现在您必须创建一个控制器。

@RequestMapping(value="/error", method = RequestMethod.GET)
public String error_404(){
    return "error_404";
}

Now edit your web.xml file and edit it like this :

现在编辑您的 web.xml 文件并像这样编辑它:

<error-page> 
  <error-code>404</error-code> 
  <location>/error</location>
</error-page>