Spring MVC: How to return custom 404 errorpages?

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

    The solution is much simpler than thought. One can use one generic ResourceNotFoundException defined as follows:

    public class ResourceNotFoundException extends RuntimeException { }
    

    then one can handle errors within every controller with an ExceptionHandler annotation:

    class MeterController {
        // ...
        @ExceptionHandler(ResourceNotFoundException.class)
        @ResponseStatus(HttpStatus.NOT_FOUND)
        public String handleResourceNotFoundException() {
            return "meters/notfound";
        }
    
        // ...
    
        @RequestMapping(value = "/{number}/edit", method = RequestMethod.GET)
        public String viewEdit(@PathVariable("number") final Meter meter,
                               final Model model) {
            if (meter == null) throw new ResourceNotFoundException();
    
            model.addAttribute("meter", meter);
            return "meters/edit";
        }
    }
    

    Every controller can define its own ExceptionHandler for the ResourceNotFoundException.

提交回复
热议问题