本文介绍了使用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
    }
}

为此,请设置属性为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>

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

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

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

08-11 04:22