【JAVA】Spring Boot 自定义处理404异常

本文介绍了一种自定义404错误页面的方法,通过继承BasicErrorController并覆盖默认的JSON和HTML响应来实现。具体包括如何设置HTTP状态码、返回自定义的JSON和HTML内容。

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

异常截图:

异常处理后的截图:

这边跳转的是 若依管理系统的404页面,可以根据需要自定义

实现代码:

package com.xhs.sso.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
import org.springframework.boot.web.servlet.error.DefaultErrorAttributes;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @desc: 自定义处理404异常
 * @author: admin
 * @date: 2022/5/26 22:34
 * @version: JDK 1.8
 */
@Slf4j
@Controller
@RequestMapping("${server.error.path:${error.path:/error}}")
class CustomErrorController extends BasicErrorController {


    public CustomErrorController(ServerProperties serverProperties) {
        super(new DefaultErrorAttributes(), serverProperties.getError());
    }

    /**
     * 覆盖默认的JSON响应
     */
    @Override
    public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {

        HttpStatus status = getStatus(request);
        Map<String, Object> map = new HashMap<String, Object>(16);
        map.put("rtnCode", "9999");
        map.put("rtnMsg", "404");
        log.info("覆盖默认的JSON响应");
        return new ResponseEntity<Map<String, Object>>(map, status);
    }

    /**
     * 覆盖默认的HTML响应
     */
    @Override
    public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) {
        //请求的状态
        response.setStatus(getStatus(request).value());
        //指定自定义的视图
        log.info("覆盖默认的HTML响应:{}","https://vue.ruoyi.vip/404");
        return new ModelAndView("redirect:https://vue.ruoyi.vip/404");
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值