问题描述
如您所知,在 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.
有办法吗?
推荐答案
在 Spring Framework 中,有多种处理异常(尤其是 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>
还可以传递一些对象到错误视图,见javadoc 用于此.
You can also pass some objects to error view, see javadoc for this.
这篇关于使用 Java 配置在 Spring 中重定向 404 错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!