自定义错误页面

专车解答

在上一篇SpringBoot集成数据持久化框架Mybatis最后提到一个问题,如何解决@Mapper注解这种开发负担。答案很简单,只需要告诉mabytis starter我们mapper接口的路径就可以了,这样就可以用更简便的方式达到同样的效果。实现代码如下:

@SpringBootApplication
@MapperScan(basePackages = "com.boot.example.mapper")
public class MybatisApplication {

    public static void main(String[] args) {
        SpringApplication.run(MybatisApplication.class, args);
    }
}

如果在启动类中添加了扫描配置,那么就需要去掉mapper接口上的注解

专车介绍

该趟专车是开往SpringBoot自定义错误页面的专车,在使用应用程序的时候,难免会出现各种各样的异常,比如500、404的异常,针对这种异常,我们需要给用户提供友好的展示界面,比如500我们可以提示用户“您的网络飞了,请稍后重试”,再比如404我们可以提示用户“您访问到外星球了”。此篇就来介绍如何针对异常自定义错误页面。

专车问题

第一个问题:如何针对不同的异常来自定义不同的友好界面?

专车分析

第一步:在父模块下面创建一个名为boot-example-error-page的子模块

第二步:子模块添加依赖


    
        org.springframework.boot
        spring-boot-starter-web
    

    
        org.springframework.boot
        spring-boot-starter-thymeleaf
    

第三步:创建控制器并实现ErrorController

@Controller
public class CustomErrorController implements ErrorController {

    @Override
    public String getErrorPath() {
        return "error";
    }

    @GetMapping("/error")
    public String error(HttpServletRequest request) {
        Object status = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);

        if (status != null) {
            int statusCode = Integer.parseInt(status.toString());

            if(statusCode == HttpStatus.NOT_FOUND.value()) {
                return "error-404";
            }
            else if(statusCode == HttpStatus.INTERNAL_SERVER_ERROR.value()) {
                return "error-500";
            }
        }
        return "error";
    }
}

第四步:创建一个控制器,用来抛出异常

@RestController
public class IndexController {

    @GetMapping("/")
    public void index() {
        throw new NullPointerException();
    }
}

第五步:创建启动类

@SpringBootApplication
public class ErrorApplication {

    public static void main(String[] args) {
        SpringApplication.run(ErrorApplication.class, args);
    }
}

第六步:在resources目录下面创建templates目录,然后分别创建对应的异常页面

错误页面:


<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
head>
<body>
    <label>custom error pagelabel>
body>
html>

404页面:


<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
head>
<body>
    <label>custom error page 404label>
body>
html>

500页面


<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
head>
<body>
    <label>custom error page 500label>
body>
html>

第七步:访问应用

访问:http://localhost:8080/会展示custom error page 500

访问http://localhost:8080/notfound会展示custom error page 404

专车总结

第一个问题:如何针对不同的异常返回自定义错误页面?自定义错误页面最主要的是要实现ErrorController,然后从request作用域中获取相应的错误码,针对不同的错误码,返回对应的页面

专车地址

[SpringBoot自定义错误页面](https://github.com/a601942905git/boot-example/tree/master/boot-example-error-page)