Trigger 404 in Spring-MVC controller?

后端 未结 14 1182
攒了一身酷
攒了一身酷 2020-11-29 14:59

How do I get a Spring 3.0 controller to trigger a 404?

I have a controller with @RequestMapping(value = \"/**\", method = RequestMethod.GET) and for som

相关标签:
14条回答
  • 2020-11-29 15:54

    Simply you can use web.xml to add error code and 404 error page. But make sure 404 error page must not locate under WEB-INF.

    <error-page>
        <error-code>404</error-code>
        <location>/404.html</location>
    </error-page>
    

    This is the simplest way to do it but this have some limitation. Suppose if you want to add the same style for this page that you added other pages. In this way you can't to that. You have to use the @ResponseStatus(value = HttpStatus.NOT_FOUND)

    0 讨论(0)
  • 2020-11-29 15:55

    Configure web.xml with setting

    <error-page>
        <error-code>500</error-code>
        <location>/error/500</location>
    </error-page>
    
    <error-page>
        <error-code>404</error-code>
        <location>/error/404</location>
    </error-page>
    

    Create new controller

       /**
         * Error Controller. handles the calls for 404, 500 and 401 HTTP Status codes.
         */
        @Controller
        @RequestMapping(value = ErrorController.ERROR_URL, produces = MediaType.APPLICATION_XHTML_XML_VALUE)
        public class ErrorController {
    
    
            /**
             * The constant ERROR_URL.
             */
            public static final String ERROR_URL = "/error";
    
    
            /**
             * The constant TILE_ERROR.
             */
            public static final String TILE_ERROR = "error.page";
    
    
            /**
             * Page Not Found.
             *
             * @return Home Page
             */
            @RequestMapping(value = "/404", produces = MediaType.APPLICATION_XHTML_XML_VALUE)
            public ModelAndView notFound() {
    
                ModelAndView model = new ModelAndView(TILE_ERROR);
                model.addObject("message", "The page you requested could not be found. This location may not be current.");
    
                return model;
            }
    
            /**
             * Error page.
             *
             * @return the model and view
             */
            @RequestMapping(value = "/500", produces = MediaType.APPLICATION_XHTML_XML_VALUE)
            public ModelAndView errorPage() {
                ModelAndView model = new ModelAndView(TILE_ERROR);
                model.addObject("message", "The page you requested could not be found. This location may not be current, due to the recent site redesign.");
    
                return model;
            }
    }
    
    0 讨论(0)
提交回复
热议问题