SpringBoot 错误页面跳转

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

}

发布了40 篇原创文章 · 获赞 31 · 访问量 62万+

猜你喜欢

转载自blog.csdn.net/weixin_38422258/article/details/104172156
今日推荐