404 error redirect in Spring with java config

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

    The solution proposed in comments above really works:

    @Override
    protected void customizeRegistration(ServletRegistration.Dynamic registration)
    {
      registration.setInitParameter("throwExceptionIfNoHandlerFound", "true");
    }
    
    0 讨论(0)
  • 2020-11-27 05:10

    Use code-based Servlet container initialization as described in the doc and override registerDispatcherServlet method to set throwExceptionIfNoHandlerFound property to true:

    public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
        @Override
        protected Class<?>[] getRootConfigClasses() {
            return null;
        }
    
        @Override
        protected Class<?>[] getServletConfigClasses() {
            return new Class[] { WebConfig.class };
        }
    
        @Override
        protected String[] getServletMappings() {
            return new String[] { "/" };
        }
    
        @Override
        protected void registerDispatcherServlet(ServletContext servletContext) {
            String servletName = getServletName();
            Assert.hasLength(servletName, "getServletName() may not return empty or null");
    
            WebApplicationContext servletAppContext = createServletApplicationContext();
            Assert.notNull(servletAppContext,
                "createServletApplicationContext() did not return an application " +
                        "context for servlet [" + servletName + "]");
    
            DispatcherServlet dispatcherServlet = new DispatcherServlet(servletAppContext);
    
            // throw NoHandlerFoundException to Controller
            dispatcherServlet.setThrowExceptionIfNoHandlerFound(true);
    
            ServletRegistration.Dynamic registration = servletContext.addServlet(servletName, dispatcherServlet);
            Assert.notNull(registration,
                "Failed to register servlet with name '" + servletName + "'." +
                        "Check if there is another servlet registered under the same name.");
    
            registration.setLoadOnStartup(1);
            registration.addMapping(getServletMappings());
            registration.setAsyncSupported(isAsyncSupported());
    
            Filter[] filters = getServletFilters();
            if (!ObjectUtils.isEmpty(filters)) {
                for (Filter filter : filters) {
                    registerServletFilter(servletContext, filter);
                }
            }
    
            customizeRegistration(registration);
        }
    }    
    

    Then create an exception handler:

    @ControllerAdvice
    public class ExceptionHandlerController {
        @ExceptionHandler(Exception.class)
        public String handleException(Exception e) {
            return "404";// view name for 404 error
        }   
    }
    

    Don't forget about using @EnableWebMvc annotation on your Spring configuration file:

    @Configuration
    @EnableWebMvc
    @ComponentScan(basePackages= {"org.project.etc"})
    public class WebConfig extends WebMvcConfigurerAdapter {
        ...
    }
    
    0 讨论(0)
  • 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";
      
          }
      }
      
    0 讨论(0)
提交回复
热议问题