默认的错误页面处理类org.springframework.boot.autoconfigure.web.BasicErrorController

添加了自定义错误处理页面的项目结构如下:

image
image

在pom.xml中需要添加下面的依赖

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
</dependency>

服务器端异常会返回500的页面,会使用500.html页面返回给客户端浏览器

如果浏览器请求的资源不存在,会返回400.html的页面给客户端浏览器

一次类推,其他的错误码页面只需要在resources/public/error下面添加即可

TestExceptionPageController.java

package com.dennis.controller;
import org.springframework.boot.autoconfigure.web.ErrorController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping({"/tepc"})
public class TestExceptionPageController {

    @RequestMapping(value="test500")
    @ResponseBody
    public String test500(){
        ErrorController  xx;
        int i = 1/0;
        return "hello";
    }
}

验证
http://localhost:8080/tepc/test500 由于1/0,会抛出一个运行时异常

image
image

http://localhost:8080/tepc/xxxx 不存在这样的资源

image
image