Spring Boot自定义错误页面

默认的错误页面比较丑,所以我们需要需要我们自定义页面来处理

 

Spring Boot默认的错误页面路径是在resources/templates/error/目录下,当发生404、500状态码时,默认会跳转到该路径下的页面

 

如果是JSP,则放在下面目录下

 

---------------------------------------------------------------------------------------------------------------------------------------------

 

 

如果不想放在默认的路径下,就集成下面配置,进行自定义

 

1. 创建ServletUtil

import javax.servlet.http.HttpServletRequest;

/**
 * ServletUtil
 *
 * @Author: hanYong
 * @CreateTime: 2019-08-28
 */
public class ServletUtil {

    /**
     * 请求格式为json
     */
    private static final String APPLICATION_JSON = "application/json";
    /**
     * 请求格式为xml
     */
    private static final String XML_HTTP_REQUEST = "XMLHttpRequest";
    /**
     * json后缀
     */
    private static final String JSON_SUFFIX = ".json";
    /**
     * xml后缀
     */
    private static final String XML_SUFFIX = ".xml";

    /**
     * 是否是Ajax异步请求
     *
     * @param request 客户端请求
     * @return boolean
     */
    public static boolean isAjaxRequest(HttpServletRequest request) {
        String accept = request.getHeader("accept");
        if (accept != null && accept.contains(APPLICATION_JSON)) {
            return true;
        }

        String xRequestedWith = request.getHeader("X-Requested-With");
        if (xRequestedWith != null && xRequestedWith.contains(XML_HTTP_REQUEST)) {
            return true;
        }

        String uri = request.getRequestURI();
        if (inStringIgnoreCase(uri, JSON_SUFFIX, XML_SUFFIX)) {
            return true;
        }

        String ajax = request.getParameter("__ajax");
        return inStringIgnoreCase(ajax, "json", "xml");
    }

    /**
     * 是否包含字符串(不区分大小写)
     *
     * @param str           验证字符串
     * @param searchStrings 字符串组
     * @return boolean
     */
    public static boolean inStringIgnoreCase(String str, String... searchStrings) {
        if (str != null && searchStrings != null) {
            for (String s : searchStrings) {
                if (str.equalsIgnoreCase(s == null ? null : s.trim())) {
                    return true;
                }
            }
        }
        return false;
    }
}

2. 创建ErrorController 

import com.example.utils.ServletUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 错误处理
 *
 * @Author: HanYong
 * @CreateTime: 2021-05-13
 */
@Controller
@RequestMapping
public class ErrorController {

    /**
     * 403 没有权限
     *
     * @return 403页面
     */
    @GetMapping("/error/403")
    public String forbidden(HttpServletRequest request) {
        if (ServletUtil.isAjaxRequest(request)) {
            // 异步请求返回json
            return "redirect:/noPermission";
        } else {
            // 403页面
            return "/error/403";
        }
    }


    /**
     * 403 没有权限(异步请求)
     *
     * @return resultBean
     */
    @RequestMapping("/noPermission")
    @ResponseBody
    public Map<String, Object> forbidden3() {
        Map<String, Object> result = new LinkedHashMap<>();
        result.put("code", 2);
        result.put("msg", "没有权限,请联系管理员授权");
        return result;
    }

    /**
     * 404 找不到页面
     *
     * @return 404页面
     */
    @GetMapping("/error/404")
    public String notFound(HttpServletRequest request) {
        if (ServletUtil.isAjaxRequest(request)) {
            // 异步请求返回json
            return "redirect:/notFound";
        } else {
            // 404页面
            return "/error/404";
        }
    }

    /**
     * 404 找不到页面(异步请求)
     *
     * @return resultBean
     */
    @RequestMapping("/notFound")
    @ResponseBody
    public Map<String, Object> notFound3() {
        Map<String, Object> result = new LinkedHashMap<>();
        result.put("code", 1);
        result.put("msg", "页面不存在");
        return result;
    }

    /**
     * 500 服务器出错
     *
     * @return 500页面
     */
    @GetMapping("/error/500")
    public String internalServerError(HttpServletRequest request) {
        if (ServletUtil.isAjaxRequest(request)) {
            // 异步请求返回json
            return "redirect:/internalServerError";
        } else {
            // 500页面
            return "/error/500";
        }
    }


    /**
     * 500 服务器出错(异步请求)
     *
     * @return resultBean
     */
    @RequestMapping("/internalServerError")
    @ResponseBody
    public Map<String, Object> internalServerError3() {
        Map<String, Object> result = new LinkedHashMap<>();
        result.put("code", 500);
        result.put("msg", "系统繁忙,请稍后重试!");
        return result;
    }
}

3.添加下面配置

/**
 * ErrorConfig
 * 根据状态码跳转到不同的页面
 *
 * @Author: hanYong
 * @CreateTime: 2019-07-15
 */
@Configuration
public class ErrorConfig {

    @Bean
    public WebServerFactoryCustomizer<ConfigurableWebServerFactory> webServerFactoryCustomizer() {
        // 不同状态码跳转到不同页面
        return (container -> container.addErrorPages(
                new ErrorPage(HttpStatus.FORBIDDEN, "/403"),
                new ErrorPage(HttpStatus.NOT_FOUND, "/404"),
                new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/500")
        ));
    }
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值