Whitelabel Error Page 专题
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; @Controller public 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<Map<String, Object>> error(HttpServletRequest request) { Map<String, Object> body = getErrorAttributes(request, getTraceParameter(request)); HttpStatus status = getStatus(request); return new ResponseEntity<Map<String, Object>>(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<String, Object> getErrorAttributes(HttpServletRequest request, boolean includeStackTrace) { RequestAttributes requestAttributes = new ServletRequestAttributes(request); Map<String, Object> 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中加入以下依赖:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
这个依赖主要是给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). * <strong>Never</strong> 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). * <strong>Never</strong> 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). * <strong>Never</strong> 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). * <strong>Never</strong> 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). * <strong>Never</strong> 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
<!DOCTYPE HTML> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>Error Pages</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> </head> <body> <p th:text="'Url:' + ${URL}" /> <p th:text="'Error:' + ${error}" /> <p th:text="'Status:' + ${status}" /> <p th:text="'Timestamp:' + ${timestamp}" /> </body> </html>
3.0 处理结果
无效请求地址均会返回此页面,只是其中的返回值不同。