使用java配置在Spring中进行404错误重定向 [英] 404 error redirect in Spring with java config

查看:1123
本文介绍了使用java配置在Spring中进行404错误重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如您所知,在XML中,配置方法是:

As you know, in XML, the way to configure this is:

<error-page>
    <error-code>404</error-code>
    <location>/my-custom-page-not-found.html</location>
</error-page>

但我还没有找到在Java配置中执行此操作的方法。我尝试的第一种方式是:

But I haven't found a way to do it in Java config. The first way I tried was:

@RequestMapping(value = "/**")
public String Error(){
    return "error";
}

它似乎有效,但它检索资源时有冲突。

And it appeared to work, but it has conflicts retrieving the resources.

有办法吗?

推荐答案

春天框架,有许多处理异常的方法(特别是404错误)。这是文档链接

In Spring Framework, there are number of ways of handing exceptions (and particularly 404 error). Here is a documentation link.


  • 首先,您仍然可以在web.xml中使用 error-page 标记,并且自定义错误页面。这是示例

  • 其次,您可以为所有控制器使用一个 @ExceptionHandler ,如下所示:

  • First, you can still use error-page tag in web.xml, and customize error page. Here is an example.
  • Second, you can use one @ExceptionHandler for all controllers, like this:

@ControllerAdvice
public class ControllerAdvisor {

     @ExceptionHandler(NoHandlerFoundException.class)
     public String handle(Exception ex) {

        return "404";//this is view name
    }
}

为此,请设置 DispatcherServlet 的javadoc-api / org / springframework / web / servlet / DispatcherServlet.html#setThrowExceptionIfNoHandlerFound-boolean - > throwExceptionIfNoHandlerFound 属性为true:

For this to work, set throwExceptionIfNoHandlerFound property to true for DispatcherServlet in web.xml:

<init-param>
    <param-name>throwExceptionIfNoHandlerFound</param-name>
    <param-value>true</param-value>
</init-param>

您还可以将一些对象传递给错误视图,参见 javadoc

You can also pass some objects to error view, see javadoc for this.

这篇关于使用java配置在Spring中进行404错误重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆