在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);
} }
} }
55
 
1
package com.haramasu.daomin2.error;
2

3
import org.slf4j.Logger;
4
import org.slf4j.LoggerFactory;
5
import org.springframework.boot.autoconfigure.web.ErrorProperties;
6
import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
7
import org.springframework.boot.web.servlet.error.ErrorAttributes;
8
import org.springframework.http.HttpStatus;
9
import org.springframework.http.MediaType;
10
import org.springframework.stereotype.Controller;
11
import org.springframework.web.bind.annotation.RequestMapping;
12
import org.springframework.web.servlet.ModelAndView;
13

14
import javax.servlet.http.HttpServletRequest;
15
import javax.servlet.http.HttpServletResponse;
16
import java.util.Collections;
17
import java.util.Map;
18

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

29
    public MyBasicErrorController(ErrorAttributes errorAttributes, ErrorProperties errorProperties) {
30
        super(errorAttributes, errorProperties);
31
    }
32

33
    @Override
34
    public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) {
35
        HttpStatus status = getStatus(request);
36
        Map<String, Object> model = Collections.unmodifiableMap(getErrorAttributes(
37
                request, isIncludeStackTrace(request, MediaType.TEXT_HTML)));
38
        response.setStatus(status.value());
39
        ModelAndView modelAndView = resolveErrorView(request, response, status, model);
40
        if(modelAndView!=null){
41
            return modelAndView;
42
        }else {
43
            String path=model.get("path").toString();
44
            logger.debug("该地址无法访问:"+path);
45
            if(path.startsWith("/admin/")){
46
                return new ModelAndView("error/adminError", model);
47
            }else {
48
                return new ModelAndView("error/homeError", model);
49
            }
50

51
        }
52
    }
53
    
54
}
55

需要注意,继承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();
}
}
1
20
 
1
package com.haramasu.daomin2.conf;
2

3
import org.springframework.boot.autoconfigure.web.ErrorProperties;
4
import org.springframework.context.annotation.Bean;
5
import org.springframework.context.annotation.Configuration;
6

7
/**
8
 * @Auther: DingShuo
9
 * @Date: 2018/7/23 12:08
10
 * @Description:
11
 */
12
@Configuration
13
public class BeanConfig  {
14

15
    @Bean
16
    public ErrorProperties errorProperties(){
17
        return new ErrorProperties();
18
    }
19
}
20


Springboot 自定义多个404页面的更多相关文章

  1. Django如何自定义漂亮的404页面

    目录 在templates 中添加404.html 修改settings.py 在templates 中添加404.html <!DOCTYPE html PUBLIC "-//W3C ...

  2. NGINX下如何自定义404页面

    什么是404页面 如果碰巧网站出了问题,或者用户试图访问一个并不存在的页面时,此时服务器会返回代码为404的错误信息,此时对应页面就是404页面.404页面的默认内容和具体的服务器有关.如果后台用的是 ...

  3. SpringBoot自定义错误页面,SpringBoot 404、500错误提示页面

    SpringBoot自定义错误页面,SpringBoot 404.500错误提示页面 SpringBoot 4xx.html.5xx.html错误提示页面 ====================== ...

  4. springboot自定义错误页面

    springboot自定义错误页面 1.加入配置: @Bean public EmbeddedServletContainerCustomizer containerCustomizer() { re ...

  5. Springboot - 自定义错误页面

    Springboot 没找到页面或内部错误时,会访问默认错误页面.这节我们来自定义错误页面. 自定义错误页面 1.在resources 目录下面再建一个 resources 文件夹,里面建一个 err ...

  6. JavaWeb 自定义404页面

    本来,Tomcat中自定义404页面不过是在web.xml文件中写4行代码的事情. 直接引用 Tomcat官方FAQ 怎样自定义404页面? 编辑web.xml <error-page> ...

  7. springboot使用之四:错误页面404处理建议

    每个项目可能都会遇到404,403,500等错误代码,如没有错误页面,则会给用户一个很不友好的界面,springboot项目同样也存在这个问题. 但在官方文档并没有相关配置信息,这就要求我们自己来实现 ...

  8. 通过修改 Apache 的配置文件 htaccess 文件实现自定义404页面

    最近在学习使用Apache服务器的配置,做一个记录. Apache下有个.htaccess文件,是Apache的一个特殊的配置文件.这个配置文件默认是没有的,要手动在各自的项目的根目录编写才行. 要实 ...

  9. Web---演示Servlet的相关类、下载技术、线程问题、自定义404页面

    Servlet的其他相关类: ServletConfig – 代表Servlet的初始化配置参数. ServletContext – 代表整个Web项目. ServletRequest – 代表用户的 ...

随机推荐

  1. JavaScript 生成32位UUID

    function uuid(){ var len=32; //32长度 var radix=16; //16进制 var chars='0123456789ABCDEFGHIJKLMNOPQRSTUV ...

  2. NOIP模拟 17.8.16

    NOIP模拟17.8.16 A 债务文件名 输入文件 输出文件 时间限制 空间限制debt.pas/c/cpp debt.in debt.out 1s 128MB[题目描述]小 G 有一群好朋友,他们 ...

  3. Leetcode766.Toeplitz Matrix托普利茨矩阵

    如果一个矩阵的每一方向由左上到右下的对角线上具有相同元素,那么这个矩阵是托普利茨矩阵. 给定一个 M x N 的矩阵,当且仅当它是托普利茨矩阵时返回 True. 示例 1: 输入: matrix = ...

  4. log4j:ERROR Could not read configuration file [log4j.properties]

    遇到这个错误,程序能够正常运行,log4j.properties也在classpath中,后来在网上查了资料,把下面这个语句去掉就好啦. PropertyConfigurator.configure( ...

  5. 【JZOJ3854】【NOIP2014八校联考第2场第2试9.28】分组(group)

    MEi Bsny所在的精灵社区有n个居民,每个居民有一定的地位和年龄,ri表示第i个人的地位,ai表示第i个人的年龄. 最近社区里要举行活动,要求几个人分成一个小组,小组中必须要有一个队长,要成为队长 ...

  6. 好玩又实用,阿里巴巴开源混沌工程工具 ChaosBlade

    减少故障的最好方法就是让问题经常性的发生.在可控范围或环境下,通过不断重复失败过程,持续提升系统的容错和弹性能力. 那么,实施一次高效的混沌工程实验,需要几步呢? 答案:2 步. ① 登陆 Chaos ...

  7. (译)Objective-C的动态特性

    这是一篇译文,原文在此,上一篇文章就是受这篇文章启发,这次干脆都翻译过来. 过去的几年中涌现了大量的Objective-C开发者.有些是从动态语言转过来的,比如Ruby或Python,有些是从强类型 ...

  8. Ui自动化测试框架

    为了提高我们的UI测试效率,我们引用Ui自动化测试框架,这里简单先描述一下,后续会详细补充: 了解一个测试框架,我们就需要了解一下源码,能看懂源码即可: 1.稳定先封装wait EC,电脑性能配置较好 ...

  9. 免费的容器架构可视化工具 | 阿里云应用高可用服务 AHAS 发布重大新特性

    工具下载链接:点这里.活动发布链接:点这里. 采用容器服务后,了解容器之间的关系及依赖是一个比较有挑战的问题.容器化改造后的实际架构模型可能与预想的架构存在较大的差异,架构师或系统运维人员需要精确地了 ...

  10. Navicat连接MySQL8.0版本时 建议升级连接客户端这个提示怎么办

    开始->mysql 8.0 command line client ->执行下面的命令//开启mysql服务mysql.server start//进入mysqlmysql -u root ...