w.s.m.s.DefaultHandlerExceptionResolver : Resolved exception caused by handler execution: org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation
Accept:text/html 时,api接口不存在时,后端会打印的错误日志【这种大量打印错误日志的行为,会不会造成IO阻塞,并使服务器挂掉】:spring webmvc的版本:5.0.9.RELEASE
2018-12-13 16:03:39.799 ERROR 14912 --- [nio-8080-exec-6] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] threw exceptionjavax.servlet.ServletException: Circular view path [error]: would dispatch back to the current handler URL [/error] again. Check your ViewResolver setup! (Hint: This may be the result of an unspecified view, due to default view name generation.) at org.springframework.web.servlet.view.InternalResourceView.prepareForRendering(InternalResourceView.java:209) ~[spring-webmvc-5.0.9.RELEASE.jar:5.0.9.RELEASE] at org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:147) ~[spring-webmvc-5.0.9.RELEASE.jar:5.0.9.RELEASE] at org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:315) ~[spring-webmvc-5.0.9.RELEASE.jar:5.0.9.RELEASE] at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1325) ~[spring-webmvc-5.0.9.RELEASE.jar:5.0.9.RELEASE] at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1069) ~[spring-webmvc-5.0.9.RELEASE.jar:5.0.9.RELEASE] at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1008) ~[spring-webmvc-5.0.9.RELEASE.jar:5.0.9.RELEASE] at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:925) ~[spring-webmvc-5.0.9.RELEASE.jar:5.0.9.RELEASE] at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:974) ~[spring-webmvc-5.0.9.RELEASE.jar:5.0.9.RELEASE] at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:866) ~[spring-webmvc-5.0.9.RELEASE.jar:5.0.9.RELEASE] at javax.servlet.http.HttpServlet.service(HttpServlet.java:635) ~[tomcat-embed-core-8.5.34.jar:8.5.34] at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:851) ~[spring-webmvc-5.0.9.RELEASE.jar:5.0.9.RELEASE] at javax.servlet.http.HttpServlet.service(HttpServlet.java:742) ~[tomcat-embed-core-8.5.34.jar:8.5.34] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-8.5.34.jar:8.5.34] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.34.jar:8.5.34] at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:728) [tomcat-embed-core-8.5.34.jar:8.5.34] at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:472) [tomcat-embed-core-8.5.34.jar:8.5.34] at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:395) [tomcat-embed-core-8.5.34.jar:8.5.34] at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:316) [tomcat-embed-core-8.5.34.jar:8.5.34] at org.apache.catalina.core.StandardHostValve.custom(StandardHostValve.java:395) [tomcat-embed-core-8.5.34.jar:8.5.34] at org.apache.catalina.core.StandardHostValve.status(StandardHostValve.java:254) [tomcat-embed-core-8.5.34.jar:8.5.34] at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:177) [tomcat-embed-core-8.5.34.jar:8.5.34] at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81) [tomcat-embed-core-8.5.34.jar:8.5.34] at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) [tomcat-embed-core-8.5.34.jar:8.5.34] at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342) [tomcat-embed-core-8.5.34.jar:8.5.34] at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:800) [tomcat-embed-core-8.5.34.jar:8.5.34] at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-8.5.34.jar:8.5.34] at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:806) [tomcat-embed-core-8.5.34.jar:8.5.34] at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1498) [tomcat-embed-core-8.5.34.jar:8.5.34] at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-8.5.34.jar:8.5.34] at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [na:1.8.0_144] at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [na:1.8.0_144] at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.5.34.jar:8.5.34] at java.lang.Thread.run(Thread.java:748) [na:1.8.0_144]2018-12-13 16:03:39.801 ERROR 14912 --- [nio-8080-exec-6] o.a.c.c.C.[Tomcat].[localhost] : Exception Processing ErrorPage[errorCode=0, location=/error]javax.servlet.ServletException: Circular view path [error]: would dispatch back to the current handler URL [/error] again. Check your ViewResolver setup! (Hint: This may be the result of an unspecified view, due to default view name generation.) at org.springframework.web.servlet.view.InternalResourceView.prepareForRendering(InternalResourceView.java:209) ~[spring-webmvc-5.0.9.RELEASE.jar:5.0.9.RELEASE] at org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:147) ~[spring-webmvc-5.0.9.RELEASE.jar:5.0.9.RELEASE] at org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:315) ~[spring-webmvc-5.0.9.RELEASE.jar:5.0.9.RELEASE] at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1325) ~[spring-webmvc-5.0.9.RELEASE.jar:5.0.9.RELEASE] at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1069) ~[spring-webmvc-5.0.9.RELEASE.jar:5.0.9.RELEASE] at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1008) ~[spring-webmvc-5.0.9.RELEASE.jar:5.0.9.RELEASE] at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:925) ~[spring-webmvc-5.0.9.RELEASE.jar:5.0.9.RELEASE] at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:974) ~[spring-webmvc-5.0.9.RELEASE.jar:5.0.9.RELEASE] at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:866) ~[spring-webmvc-5.0.9.RELEASE.jar:5.0.9.RELEASE] at javax.servlet.http.HttpServlet.service(HttpServlet.java:635) ~[tomcat-embed-core-8.5.34.jar:8.5.34] at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:851) ~[spring-webmvc-5.0.9.RELEASE.jar:5.0.9.RELEASE] at javax.servlet.http.HttpServlet.service(HttpServlet.java:742) ~[tomcat-embed-core-8.5.34.jar:8.5.34] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-8.5.34.jar:8.5.34] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.34.jar:8.5.34] at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:728) ~[tomcat-embed-core-8.5.34.jar:8.5.34] at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:472) ~[tomcat-embed-core-8.5.34.jar:8.5.34] at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:395) ~[tomcat-embed-core-8.5.34.jar:8.5.34] at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:316) ~[tomcat-embed-core-8.5.34.jar:8.5.34] at org.apache.catalina.core.StandardHostValve.custom(StandardHostValve.java:395) [tomcat-embed-core-8.5.34.jar:8.5.34] at org.apache.catalina.core.StandardHostValve.status(StandardHostValve.java:254) [tomcat-embed-core-8.5.34.jar:8.5.34] at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:177) [tomcat-embed-core-8.5.34.jar:8.5.34] at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81) [tomcat-embed-core-8.5.34.jar:8.5.34] at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) [tomcat-embed-core-8.5.34.jar:8.5.34] at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342) [tomcat-embed-core-8.5.34.jar:8.5.34] at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:800) [tomcat-embed-core-8.5.34.jar:8.5.34] at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-8.5.34.jar:8.5.34] at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:806) [tomcat-embed-core-8.5.34.jar:8.5.34] at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1498) [tomcat-embed-core-8.5.34.jar:8.5.34] at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-8.5.34.jar:8.5.34] at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [na:1.8.0_144] at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [na:1.8.0_144] at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.5.34.jar:8.5.34] at java.lang.Thread.run(Thread.java:748) [na:1.8.0_144]
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 处理结果
无效请求地址均会返回此页面,只是其中的返回值不同。Spring Boot Remove Whitelabel Error Page:You need to change your code to the following:@RestControllerpublic class IndexController implements ErrorController{ private static final String PATH = "/error"; @RequestMapping(value = PATH) public String error() { return "Error handling"; } @Override public String getErrorPath() { return PATH; }}
Your code did not work, because Spring Boot automatically registers the BasicErrorController as a Spring Bean when you have not specified an implementation of ErrorController.
To see that fact just navigate to ErrorMvcAutoConfiguration.basicErrorControllerYou can remove it completely by specifying:import org.springframework.context.annotation.Configuration;import org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration;...@Configuration@EnableAutoConfiguration(exclude = {ErrorMvcAutoConfiguration.class})public static MainApp { ... }
However, do note that doing so will probably cause servlet container's whitelabel pages to show up instead :)
EDIT: Another way to do this is via application.yaml. Just put in the value:spring: autoconfigure: exclude: org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration
https://stackoverflow.com/questions/25356781/spring-boot-remove-whitelabel-error-page