小编典典

使用Java配置在Spring中发生404错误重定向

spring

如你所知,在XML中,配置方式如下:

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

但是我还没有找到在Java配置中做到这一点的方法。我尝试的第一种方法是:

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

它似乎有效,但是在检索资源方面存在冲突。

有办法吗?


阅读 861

收藏
2020-04-12

共1个答案

小编典典

在Spring Framework中,有许多处理异常(尤其是404错误)的方法.

首先,你仍然可以error-page在web.xml中使用标签,并自定义错误页面。这是一个例子。
其次,可以@ExceptionHandler对所有控制器使用一个,如下所示:

@ControllerAdvice
public class ControllerAdvisor {

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

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

为此,请将web.xml中的throwExceptionIfNoHandlerFound属性设置为true DispatcherServlet

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

你还可以将一些对象传递到错误视图

2020-04-12