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

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

 
 
 
 

SpringBoot接口服务处理Whitelabel Error Page(转)的更多相关文章

  1. SpringBoot接口服务处理Whitelabel Error Page

    转载请注明来源:http://blog.csdn.net/loongshawn/article/details/50915979 <SpringBoot接口服务处理Whitelabel Erro ...

  2. 《Springboot极简教程》问题解决:Springboot启动报错 Whitelabel Error Page: This application has no explicit mapping for(转)

    13.2 Spring Boot启动报错:Whitelabel Error Page 13.2 Spring Boot启动报错:Whitelabel Error Page 问题描述 Whitelabe ...

  3. SpringBoot入门报错 Whitelabel Error Page的总结

    刚入门SpringBoot,编写helloControl类,去访问本地端口,无缘无故报了这个错误 Whitelabel Error Page 总结了下,目前我碰到的有三种会导致这种情况 1.当你的 S ...

  4. 关于Springboot启动报错 Whitelabel Error Page: This application has no explicit mapping

    Whitelabel Error Page This application has no explicit mapping for /error, so you are seeing this as ...

  5. SpringBoot Whitelabel Error Page This application has no explicit mapping for /error, so you are seeing this as a fallback.

    使用SpringBoot写HelloWorld,当配置好启动类后,再创建新的controller或其它类,启动项目后访问对应的映射名,页面显示: Whitelabel Error Page This ...

  6. 新建SpringBoot项目运行页面报错Whitelabel Error Page This application has no explicit mapping for /error, so yo

    新建SpringBoot项目运行页面报错Whitelabel Error Page This application has no explicit mapping for /error, so yo ...

  7. springboot报错Whitelabel Error Page

    第一次使用springboot没有问题.隔了两天继续看.一直报错Whitelabel Error Page. 重新搭建试了任何方法都错了. 报的就是一个404错误,犯了一个习惯性错误,一般都是loca ...

  8. SpringBoot启动项目之后,访问页面出现Whitelabel Error Page

    话说万事具备,只欠东风- 蹭闲暇时来跑个SpringBoot项目玩玩,把一切配置依赖准备就绪之后打算运行项目. Staring...... 接着,在浏览器输入地址 localhost:8080/hel ...

  9. springboot项目出现Whitelabel Error Page的问题

    springboot项目出现Whitelabel Error Page的问题 大概就是这种情况,然而昨天还是没问题的,通过对比就发现,是自己手欠了 简单来说解决办法就是将springboot的启动项目 ...

随机推荐

  1. JavaScipt实现倒计时方法总结

    JavaScript中提供了两种实现计时.延时的方法,分别如下: 一. t = setTimeout(“function()", millisecond) 与 clearTimeout(t) ...

  2. frame.origin.x 的意思和作用?

    frame.origin.x 的意思和作用? scrollView.frame 一个view的frame 包含它的矩形形状(size)的长和宽. 和它在父视图中的坐标原点(origin)x和y坐标 f ...

  3. 如何得到Sessionid的值

    当用户向一个网站请求第一个页面时,用户会话启动.当第一个页面被请求时,web服务器将asp.net_sessionID  cookie添加进用户的浏览器.可以使用newsession属性探测新会话的启 ...

  4. BootStrap 智能表单系列 十一 级联下拉的支持

    像省市县选择的这种,但凡是个人肯定都见过,实现方式有很多种 1.有在第一级选择的时候去加载或者从本地对象中拿第一级对应的数据源显示到列表中,第二级以此类推 2.也有将所有的项都加载到select中,然 ...

  5. js获取智能机浏览器版本信息

    <!DOCTYPE html><html> <head>        <meta charset="UTF-8">         ...

  6. MVC过滤器进行统一登录验证

    统一登录验证: 1.定义实体类Person:利用特性标签验证输入合法性设计登录页面 1 2 3 4 5 6 7 8 9 public class Person {     [DisplayName(& ...

  7. iOS 10 因苹果健康导致闪退 crash

    如果在app中调用了苹果健康,iOS10中会出现闪退.控制台报出的原因是: Terminating app due to uncaught exception 'NSInvalidArgumentEx ...

  8. BZOJ 2466: [中山市选2009]树( 高斯消元 )

    高斯消元解异或方程组...然后对自由元进行暴搜.树形dp应该也是可以的... ------------------------------------------------------------- ...

  9. centos 挂载windows共享目录

    su (获取root权限) yum install samba 安装samba (其实我们只用到samba里面的winbind以便我们能够用windows机器的名称找到该机器的网络地址,在下面叙述的过 ...

  10. 帝国cms后台 不同栏目发布字段不同

    在同一数据表下的两个栏目,由于功能不同,也需要建立不同的字段,问题是建立完不同字段后,其数据表下的两个栏目都有发布字段.这里教大家,不同栏目下发布内容,不同字段.修改数据模型中 录入表单模板 代码.底 ...