Spring MVC: How to return custom 404 errorpages?

后端 未结 8 2148
遇见更好的自我
遇见更好的自我 2020-11-27 04:40

I\'m looking for a clean way to return customized 404 errorpages in Spring 4 when a requested resource was not found. Queries to different domain types should result in diff

8条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-27 05:16

    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[] { "/" };
      }
      
      //that's important!!
      @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";
      
      }
      

      }

    3. Create 404.jsp page with any content

    That's all.

提交回复
热议问题