博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Whitelabel Error Page 专题
阅读量:6250 次
发布时间:2019-06-22

本文共 10829 字,大约阅读时间需要 36 分钟。

Spring boot为错误视图提供了如下错误属性:

timestamp:错误发生的时间
status:HTTP状态码
error:错误原因
exception:异常的类名
message:异常消息(如果这个错误是由异常引起的)
errors:BindsResult异常里的各种错误(如果这个错误是由异常引起的)
trace:异常跟踪信息(如果这个错误是由异常引起的)
path:错误发生时请求的URL路径

test To switch it off you can set server.error.whitelabel.enabled=false

 

错误问题会发生的,那些在生产环境里最健壮的应用程序偶尔也会遇到麻烦。虽然减少用户遇到错误的概率很重要,但让应用程序展现一个好的错误页面也同样重要

Spring Boot默认提供这个whitelabel错误页,是自动配置的一部分。

Spring Boot自动配置的默认错误处理器会查找名为error的视图,如果找不到就用默认的whitelabel视图。因此最简单的方法就是创建一个自定义视图,让解析出的视图名为error

要达到预期的效果,需要有下面一项视图解析器的配置:
(1)实现了Spring的View接口的Bean,其ID为error(由Spring的BeanNameViewResolver所解析)
(2)如果配置了Thymeleaf,则有名为error.html的Thymeleaf模板
(3)如果配置了FreeMarker,则有名为error.ftl的FreeMarker模板
(4)如果配置了Velocity,则有名为error.vm的Velocity模板
(5)如果是用JSP视图,则有名为error.jsp的JSP模板
当然视图解析器要知道这个error的模板文件。

 

异常说明

SpringBoot搭建的接口服务,如果请求非注册类的无效接口地址,则返回该页面。主要问题就是没有对异常请求做处理。

举例,定义有效接口地址如:http://ip/user, http://ip/age。则其它地址均为无效地址,若请求则返回上述Whitelabel Error Page页面。

 

2.0 异常处理

主要是添加一个AppErrorController的Controller类,这里我定义了异常返回页面。

import java.util.Map;import javax.servlet.http.HttpServletRequest;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.autoconfigure.web.ErrorAttributes;import org.springframework.boot.autoconfigure.web.ErrorController;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.bind.annotation.ResponseBody;import org.springframework.web.context.request.RequestAttributes;import org.springframework.web.context.request.ServletRequestAttributes;import org.springframework.web.servlet.ModelAndView;@Controllerpublic class AppErrorController implements ErrorController{    private static final Logger logger = LoggerFactory.getLogger(AppErrorController.class);    private static AppErrorController appErrorController;     /**     * Error Attributes in the Application     */    @Autowired    private ErrorAttributes errorAttributes;    private final static String ERROR_PATH = "/error";    /**     * Controller for the Error Controller     * @param errorAttributes     * @return      */     public AppErrorController(ErrorAttributes errorAttributes) {        this.errorAttributes = errorAttributes;    }    public AppErrorController() {        if(appErrorController == null){            appErrorController = new AppErrorController(errorAttributes);        }    }    /**     * Supports the HTML Error View     * @param request     * @return     */    @RequestMapping(value = ERROR_PATH, produces = "text/html")    public ModelAndView errorHtml(HttpServletRequest request) {        return new ModelAndView("greeting", getErrorAttributes(request, false));    }    /**     * Supports other formats like JSON, XML     * @param request     * @return     */    @RequestMapping(value = ERROR_PATH)    @ResponseBody    public ResponseEntity
> error(HttpServletRequest request) { Map
body = getErrorAttributes(request, getTraceParameter(request)); HttpStatus status = getStatus(request); return new ResponseEntity
>(body, status); } /** * Returns the path of the error page. * * @return the error path */ @Override public String getErrorPath() { return ERROR_PATH; } private boolean getTraceParameter(HttpServletRequest request) { String parameter = request.getParameter("trace"); if (parameter == null) { return false; } return !"false".equals(parameter.toLowerCase()); } private Map
getErrorAttributes(HttpServletRequest request, boolean includeStackTrace) { RequestAttributes requestAttributes = new ServletRequestAttributes(request); Map
map = this.errorAttributes.getErrorAttributes(requestAttributes,includeStackTrace); String URL = request.getRequestURL().toString(); map.put("URL", URL); logger.debug("AppErrorController.method [error info]: status-" + map.get("status") +", request url-" + URL); return map; } private HttpStatus getStatus(HttpServletRequest request) { Integer statusCode = (Integer) request .getAttribute("javax.servlet.error.status_code"); if (statusCode != null) { try { return HttpStatus.valueOf(statusCode); } catch (Exception ignored) { } } return HttpStatus.INTERNAL_SERVER_ERROR; } }

这个类实现了ErrorController接口,用来处理请求的各种异常。其中定义了一个greeting的html模版,用来显示返回结果。

初始化此类模版需要在pom中加入以下依赖:

org.springframework.boot
spring-boot-starter-thymeleaf

这个依赖主要是给SpringBoot中加载html等类型的模版服务。其支持的模版类型如下:

Template modes:[THYMELEAF]     * XHTML[THYMELEAF]     * XML[THYMELEAF]     * HTML5[THYMELEAF]     * LEGACYHTML5[THYMELEAF]     * VALIDXHTML[THYMELEAF]     * VALIDXML

org.thymeleaf.templatemode.TemplateMode

/* * ============================================================================= * *   Copyright (c) 2011-2016, The THYMELEAF team (http://www.thymeleaf.org) * *   Licensed under the Apache License, Version 2.0 (the "License"); *   you may not use this file except in compliance with the License. *   You may obtain a copy of the License at * *       http://www.apache.org/licenses/LICENSE-2.0 * *   Unless required by applicable law or agreed to in writing, software *   distributed under the License is distributed on an "AS IS" BASIS, *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *   See the License for the specific language governing permissions and *   limitations under the License. * * ============================================================================= */package org.thymeleaf.templatemode;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.thymeleaf.TemplateEngine;import org.thymeleaf.templateresolver.AbstractConfigurableTemplateResolver;/** * * @author Daniel Fernández * * @since 3.0.0 * */public enum TemplateMode {    HTML(true, false, false), XML(false, true, false),    TEXT(false, false, true), JAVASCRIPT(false, false, true), CSS(false, false, true),    RAW(false, false, false),    /**     * Provided only for legacy compatibility reasons for old XML-based configurations (e.g. Spring).     * Never use this value directly. Only to be used internally at     * {
@link AbstractConfigurableTemplateResolver} implementations. * * @deprecated Deprecated in 3.0.0. Use {
@link #HTML} instead. Will be REMOVED in 3.1 */ @Deprecated HTML5(true, false, false), /** * Provided only for legacy compatibility reasons for old XML-based configurations (e.g. Spring). * Never use this value directly. Only to be used internally at * {
@link AbstractConfigurableTemplateResolver} implementations. * * @deprecated Deprecated in 3.0.0. Use {
@link #HTML} instead. Will be REMOVED in 3.1 */ @Deprecated LEGACYHTML5(true, false, false), /** * Provided only for legacy compatibility reasons for old XML-based configurations (e.g. Spring). * Never use this value directly. Only to be used internally at * {
@link AbstractConfigurableTemplateResolver} implementations. * * @deprecated Deprecated in 3.0.0. Use {
@link #HTML} instead. Will be REMOVED in 3.1 */ @Deprecated XHTML(true, false, false), /** * Provided only for legacy compatibility reasons for old XML-based configurations (e.g. Spring). * Never use this value directly. Only to be used internally at * {
@link AbstractConfigurableTemplateResolver} implementations. * * @deprecated Deprecated in 3.0.0. Use {
@link #HTML} instead. Will be REMOVED in 3.1 */ @Deprecated VALIDXHTML(true, false, false), /** * Provided only for legacy compatibility reasons for old XML-based configurations (e.g. Spring). * Never use this value directly. Only to be used internally at * {
@link AbstractConfigurableTemplateResolver} implementations. * * @deprecated Deprecated in 3.0.0. Use {
@link #XML} instead. Will be REMOVED in 3.1 */ @Deprecated VALIDXML(false, true, false); private static Logger logger = LoggerFactory.getLogger(TemplateMode.class); private final boolean html; private final boolean xml; private final boolean text; private final boolean caseSensitive; TemplateMode(final boolean html, final boolean xml, final boolean text) { this.html = html; this.xml = xml; this.text = text; this.caseSensitive = !this.html; } public boolean isMarkup() { return this.html || this.xml; } public boolean isText() { return this.text; } public boolean isCaseSensitive() { return this.caseSensitive; } public static TemplateMode parse(final String mode) { if (mode == null || mode.trim().length() == 0) { throw new IllegalArgumentException("Template mode cannot be null or empty"); } if ("HTML".equalsIgnoreCase(mode)) { return HTML; } if ("XML".equalsIgnoreCase(mode)) { return XML; } if ("TEXT".equalsIgnoreCase(mode)) { return TEXT; } if ("JAVASCRIPT".equalsIgnoreCase(mode)) { return JAVASCRIPT; } if ("CSS".equalsIgnoreCase(mode)) { return CSS; } if ("RAW".equalsIgnoreCase(mode)) { return RAW; } // Legacy template modes are automatically converted here // This code should probably be removed at some point in the distant future after Thymeleaf v3 if ("HTML5".equalsIgnoreCase(mode) || "XHTML".equalsIgnoreCase(mode) || "VALIDXHTML".equalsIgnoreCase(mode) || "LEGACYHTML5".equalsIgnoreCase(mode)) { logger.warn( "[THYMELEAF][{}] Template Mode '{}' is deprecated. Using Template Mode '{}' instead.", new Object[]{TemplateEngine.threadIndex(), mode, HTML}); return HTML; } if ("VALIDXML".equalsIgnoreCase(mode)) { logger.warn( "[THYMELEAF][{}] Template Mode '{}' is deprecated. Using Template Mode '{}' instead.", new Object[]{TemplateEngine.threadIndex(), mode, XML}); return XML; } logger.warn( "[THYMELEAF][{}] Unknown Template Mode '{}'. Must be one of: 'HTML', 'XML', 'TEXT', 'JAVASCRIPT', 'CSS', 'RAW'. " + "Using default Template Mode '{}'.", new Object[]{TemplateEngine.threadIndex(), mode, HTML}); return HTML; }}

SpringBoot项目配置模版路径的方法如下:

1、在main的resources路径下新建templates文件夹

2、在templates文件夹中新建模版文件greeting.html

    Error Pages    

3.0 处理结果

无效请求地址均会返回此页面,只是其中的返回值不同。

 

转载地址:http://rafsa.baihongyu.com/

你可能感兴趣的文章
获取当前程序的路径
查看>>
Mysql InnoDB锁
查看>>
Rabbit-service Message queue MQ 验证 校验
查看>>
fopen/fclose
查看>>
NTP DDOS攻击
查看>>
zabbix2.2.3 VMware Vsphere exsi监控配置步骤
查看>>
正则表达式
查看>>
疯狂Android入门_事件处理
查看>>
第五次作业:结对项目-四则运算 “软件”之升级版
查看>>
k8s集群安装
查看>>
JavaWeb项目中文乱码问题
查看>>
hdu1827 有向图的强连通分量/缩点-tarjan
查看>>
存储管理
查看>>
求子数组最大和
查看>>
《数据结构与算法》-1-绪论
查看>>
SpringMvc文件上传
查看>>
shell之列表的定义与循环
查看>>
关于卡尔曼滤波
查看>>
修改servlet无需重启tomcat
查看>>
关于lvs+keepalived只加入一台realserver问题
查看>>