SpringBoot 错误页面跳转

本文介绍如何在SpringBoot中配置自定义错误页面,包括400、401、404和500错误,通过创建错误页面配置类和错误页面跳转控制器实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

SpringBoot实现MVC 404、500等错误时跳转自定义页面

一、新增配置类

package com.study.demo.config;


import org.springframework.boot.web.server.ErrorPage;
import org.springframework.boot.web.server.ErrorPageRegistrar;
import org.springframework.boot.web.server.ErrorPageRegistry;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

/**
 * 错误页面的配置
 */
@Component
public class ErrorPageConfig implements ErrorPageRegistrar {
    @Override
    public void registerErrorPages(ErrorPageRegistry registry) {
        ErrorPage error400Page = new ErrorPage(HttpStatus.BAD_REQUEST, "/errorPageController/error_400");
        ErrorPage error401Page = new ErrorPage(HttpStatus.UNAUTHORIZED, "/errorPageController/error_401");
        ErrorPage error404Page = new ErrorPage(HttpStatus.NOT_FOUND, "/errorPageController/error_404");
        ErrorPage error500Page = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/errorPageController/error_500");
        registry.addErrorPages(error400Page,error401Page,error404Page,error500Page);
    }
}

二、错误页面跳转控制器

package com.study.demo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/errorPageController")
public class ErrorPageController {

    @RequestMapping("/error_{errorCode}")
    public String error(@PathVariable int errorCode){
        String responseMsg;
        switch (errorCode) {
            case 400: responseMsg = "/400.html"; break;
            case 401: responseMsg = "/401.html"; break;
            case 404: responseMsg = "/404.html"; break;
            case 500: responseMsg = "/500.html"; break;
            default: responseMsg = "/404.html"; break;
        }
        return responseMsg;
    }

}

评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值