Springboot 自定义多个404页面

在Springboot中,可以通过修改配置、或者在static文件夹下添加error文件夹引入个性化的404模版。但是如果需要针对不同url地址规则,返回不同样式的404页面,则难以实现了。针对这个问题,可以参考如下内容。

例如有两种类型的url:
/admin开头的是后台管理,其他url为常规访问,不考虑安全性的情况下,想返回两种样式的404页面。

Springboot中的错误页面均是由BasicErrorController控制,继承BasicErrorController,重写其中方法即可实现自定义错误页面。
package com.haramasu.daomin2.error;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
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.Collections;
import java.util.Map;

/**
 * @Auther: DingShuo
 * @Date: 2018/7/23 12:25
 * @Description:
 */
@Controller
@RequestMapping(value = "/error")
public class MyBasicErrorController extends BasicErrorController {
    Logger logger =LoggerFactory.getLogger(MyBasicErrorController.class);

    public MyBasicErrorController(ErrorAttributes errorAttributes, ErrorProperties errorProperties) {
        super(errorAttributes, errorProperties);
    }

    @Override
    public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) {
        HttpStatus status = getStatus(request);
        Map<String, Object> model = Collections.unmodifiableMap(getErrorAttributes(
                request, isIncludeStackTrace(request, MediaType.TEXT_HTML)));
        response.setStatus(status.value());
        ModelAndView modelAndView = resolveErrorView(request, response, status, model);
        if(modelAndView!=null){
            return modelAndView;
        }else {
            String path=model.get("path").toString();
            logger.debug("该地址无法访问:"+path);
            if(path.startsWith("/admin/")){
                return new ModelAndView("error/adminError", model);
            }else {
                return new ModelAndView("error/homeError", model);
            }

        }
    }
    
}
需要注意,继承BasicErrorController后的构造函数,会提示errorProperties的bean未被初始化。
可以在@Configration注解的类中初始化bean
package com.haramasu.daomin2.conf;

import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @Auther: DingShuo
 * @Date: 2018/7/23 12:08
 * @Description:
 */
@Configuration
public class BeanConfig  {

    @Bean
    public ErrorProperties errorProperties(){
        return new ErrorProperties();
    }
}





posted @ 2018-07-23 13:16  二刀  阅读(2767)  评论(0编辑  收藏  举报