Spring MVC:如何返回自定义404错误页面?

Spring MVC:如何返回自定义404错误页面?,第1张

Spring MVC:如何返回自定义404错误页面?

解决方案比想像的要简单得多。可以使用一种通用

ResourceNotFoundException
定义,如下所示:

public class ResourceNotFoundException extends RuntimeException { }

然后可以使用

ExceptionHandler
注释处理每个控制器中的错误:

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";    }}

每个控制器都可

ExceptionHandler
以为定义自己的控制器
ResourceNotFoundException



欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5564881.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-14
下一篇 2022-12-14

发表评论

登录后才能评论

评论列表(0条)

保存