404 error redirect in Spring with java config

前端 未结 9 1195
-上瘾入骨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:13

    Simple answer for 100% free xml:

    1. Set properties for DispatcherServlet

      public class SpringMvcInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
      
          @Override
          protected Class[] getRootConfigClasses() {
              return new Class[] { RootConfig.class  };
          }
      
          @Override
          protected Class[] getServletConfigClasses() {
              return new Class[] {AppConfig.class  };
          }
      
          @Override
          protected String[] getServletMappings() {
              return new String[] { "/" };
          }
      
          @Override
          protected void customizeRegistration(ServletRegistration.Dynamic registration) {
              boolean done = registration.setInitParameter("throwExceptionIfNoHandlerFound", "true"); // -> true
              if(!done) throw new RuntimeException();
          }
      
      }
      
    2. Create @ControllerAdvice:

      @ControllerAdvice
      public class AdviceController {
      
          @ExceptionHandler(NoHandlerFoundException.class)
          public String handle(Exception ex) {
              return "redirect:/404";
          }
      
          @RequestMapping(value = {"/404"}, method = RequestMethod.GET)
          public String NotFoudPage() {
              return "404";
      
          }
      }
      

提交回复
热议问题