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

http://stackoverflow.com/questions/25356781/spring-boot-remove-whitelabel-error-page/25362790

转载请注明来源:http://blog.csdn.net/loongshawn/article/details/50915979

1.0 异常说明

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

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

2.0 异常处理

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

package com.autonavi.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;

/**
 * <p>Author: loongshawn
 * <p>Date: 16-03-17
 * <p>Version: 1.0
 */
@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 ex) {
            }
        }
        return HttpStatus.INTERNAL_SERVER_ERROR;
    }   

}

这个类实现了ErrorController接口,用来处理请求的各种异常。其中定义了一个greeting的html模版,用来显示返回结果。初始化此类模版需要在pom中加入以下依赖:

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
  • 1
  • 2
  • 3
  • 4

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

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

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 处理结果

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

 
 

http://blog.csdn.net/loongshawn/article/details/50915979

转载请注明来源:http://blog.csdn.net/loongshawn/article/details/50915979

1.0 异常说明

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

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

2.0 异常处理

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

package com.autonavi.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;

/**
 * <p>Author: loongshawn
 * <p>Date: 16-03-17
 * <p>Version: 1.0
 */
@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 ex) {
            }
        }
        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
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

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 处理结果

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

 
 
 
 

最新文章

  1. 每日设置Bing首页图片为壁纸
  2. 【虚拟机】在VMware中安装Server2008之后配置网络连接的几种方式
  3. Chrome console命令整理
  4. php绘图问题
  5. JS向光标指定位置插入内容
  6. iOS常用正则表达式验证(手机号、密码格式、身份证号等)
  7. Javascript——说说js的调试
  8. Codeforces Gym 100418J Lucky tickets 数位DP
  9. XPATH 注入的介绍与代码防御
  10. 阿里IPO弃港赴美?
  11. 【转】C++实现RTMP协议发送H.264编码及AAC编码的音视频
  12. 使用 voluptuous 校验数据
  13. 汇编语言2(mooc)
  14. Windows Azure开发之Linux虚拟机
  15. curl命令基本使用小总结
  16. fileInputStream.available()获取 文件的总大小
  17. hive 动态分区实现 (hive-1.1.0)
  18. java锁类型
  19. JS 自定义对象 属性
  20. qt Cannot connect creator comm socket /tmp/qt_temp.S26613/stub-socket: No such

热门文章

  1. c#打印记忆功能
  2. CCTableView 简单样例
  3. android UI进阶之用【转】
  4. 【HDU】病毒侵袭持续中(AC自己主动机+map)
  5. jQuery的hover()方法(笔记)
  6. flexbox 伸缩布局盒
  7. POJ 2115 模线性方程 ax=b(mod n)
  8. SQL Server 2012学习笔记 1 命令行安装
  9. TreeSet两种比较
  10. 从零开始写驱动——vfd专用驱动芯片HT16514并行驱动程序编写