本文共 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
这个类实现了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/