如何通过在SpringMVC中返回自定义错误页来全局处理404异常?

如何通过在SpringMVC中返回自定义错误页来全局处理404异常?,spring,spring-mvc,exception-handling,Spring,Spring Mvc,Exception Handling,我需要为HTTP404返回一个定制的错误页面,但是代码不起作用。我已经阅读了stackflow、、和different+,但我的案例与它们大不相同,或者至少我无法理解这个问题 HTTP Status 404 - type Status report message description The requested resource is not available. 例如,有人建议在web.xml中使用一个操作名来处理异常,它可能会工作,但我认为这不是一个好方法 我使用了以下组合: 1

我需要为HTTP404返回一个定制的错误页面,但是代码不起作用。我已经阅读了stackflow、、和different+,但我的案例与它们大不相同,或者至少我无法理解这个问题

HTTP Status 404 -

type Status report

message

description The requested resource is not available.
例如,有人建议在web.xml中使用一个操作名来处理异常,它可能会工作,但我认为这不是一个好方法

我使用了以下组合:

1)

@Controller   //for class
@ResponseStatus(value = HttpStatus.NOT_FOUND) //for method

2)
 @Controller   //for class
 @ResponseStatus(value = HttpStatus.NOT_FOUND) //for method
 @ExceptionHandler(ResourceNotFoundException.class) //for method

3)

@ControllerAdvice //for class
@ResponseStatus(value = HttpStatus.NOT_FOUND) //for method

3)

@ControllerAdvice //for class
@ResponseStatus(HttpStatus.NOT_FOUND) //for method

4)
 @ControllerAdvice   //for class
 @ResponseStatus(value = HttpStatus.NOT_FOUND) //for method
 @ExceptionHandler(ResourceNotFoundException.class) //for method
代码

@ControllerAdvice
public class GlobalExceptionHandler {
    @ResponseStatus(value = HttpStatus.NOT_FOUND)
    public String handleBadRequest(Exception exception) {
          return "error404";
    }
}

您可以在类级别使用@ResponseStatus注释。至少对我有用

@Controller
@ResponseStatus(value=HttpStatus.NOT_FOUND)
public class GlobalExceptionHandler {
  ....  
}

DispatcherServlet
如果未找到处理请求的处理程序,则默认情况下不会引发异常。因此,您需要按如下方式显式激活它:

在web.xml中:

<servlet>
    <servlet-name>mvc-dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>throwExceptionIfNoHandlerFound</param-name>
        <param-value>true</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>
在控制器建议类中:

@ExceptionHandler
@ResponseStatus(HttpStatus.NOT_FOUND)
public String handleExceptiond(NoHandlerFoundException ex) {
    return "errorPage";
}

您可以在web.xml中添加以下内容,以在404上显示错误页面。它将在WEB-INF文件夹中的视图文件夹中显示404.jsp页面

 <error-page>
    <error-code>404</error-code>
    <location>/WEB-INF/views/404.jsp</location>
 </error-page>

404
/WEB-INF/views/404.jsp

它可以正常工作,谢谢,但问题是我应该为每种类型的httpstatus单独设置一个类。很抱歉,我不确定该问题,但无法自定义此页面,我需要向后端发送一个请求,以根据每个请求发送一个自定义错误页面。谢谢,我正在使用注释,我应该在哪里使用该行?@Jack是在web.XML中配置的DispatcherServlet吗?是的,它在web.XML中配置,那么您只需要进行我在回答中提到的XML更改。
 <error-page>
    <error-code>404</error-code>
    <location>/WEB-INF/views/404.jsp</location>
 </error-page>