Spring MVC: How to return custom 404 errorpages?

后端 未结 8 2023
遇见更好的自我
遇见更好的自我 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:10

    modified your web.xml file.Using following code.

    <display-name>App Name </display-name>
    <error-page>
    <error-code>500</error-code>
    <location>/error500.jsp</location>
    </error-page>
    
    <error-page>
    <error-code>404</error-code>
    <location>/error404.jsp</location>
    </error-page>
    

    Access this by following code.

    response.sendError(508802,"Error Message");
    

    Now add this code in web.xml.

    <error-page>
    <error-code>508802</error-code>
    <location>/error500.jsp</location>
    </error-page>
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题