404 error redirect in Spring with java config

前端 未结 9 1190
-上瘾入骨i
-上瘾入骨i 2020-11-27 04:46

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


    404
    /my-custom-page-not-fo         


        
9条回答
  •  鱼传尺愫
    2020-11-27 05:06

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

    • 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
          }
      }
      

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

      
          throwExceptionIfNoHandlerFound
          true
      
      

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

提交回复
热议问题