当前位置:   article > 正文

SpringBoot 错误页面跳转_spring boot页面跳转报错

spring boot页面跳转报错

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

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

二、错误页面跳转控制器

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

}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Gausst松鼠会/article/detail/210916
推荐阅读
相关标签
  

闽ICP备14008679号