Что означает whitelabel error page

Русские Блоги Основная причина страницы ошибки SpringBoot Whitelabel, три решения и их характеристики 0, краткое описание Перед изучением этой заметки

Содержание

  1. Русские Блоги
  2. Основная причина страницы ошибки SpringBoot Whitelabel, три решения и их характеристики
  3. 0, краткое описание
  4. 1. Страница ошибки Whitelabel
  5. 2. Решите проблему с белой страницей.
  6. Spring выдает ошибку Whitelabel error page, что не так?
  7. Внутренняя ошибка сервера 500 в Госуслуги — как исправить
  8. Error 500: причины появления бага
  9. Произошла ошибка 500: устраняем в 2 способа
  10. Стандартное руководство для обычных пользователей
  11. Инструкция для админов
  12. Что еще нужно знать админу?
  13. Выводы

Русские Блоги

Основная причина страницы ошибки SpringBoot Whitelabel, три решения и их характеристики

0, краткое описание

Перед изучением этой заметки лучше всего иметь некоторое представление о Spring mvc и Tomcat, чтобы было удобнее понимать.Если вам нужно знать наиболее прямое решение, перетащите его вниз, чтобы увидеть образец кода.

Вводится настоящая причина появления белой страницы Springboot. Основная причина заключается в том, что нет подходящей ситуации соответствия и возникает ситуация 404. Затем перейдите к системной по умолчанию сначала ErrorPage, которая представляет собой содержимое белой страницы, а затем с трех точек зрения в соответствии с его спецификой. , 1. Перехватчик, 2. Новая страница ошибок, 3. Пользовательская маршрутизация / маршрутизация ошибок для решения проблемы, а также знакомство с преимуществами и недостатками каждого метода, включая основные причины ошибок страницы цикла и т. Д.

1. Страница ошибки Whitelabel

То, что называется страницей ошибок Whitelabel (также называемой белой страницей), является страницей описания аномального HTTP-запроса в SpringBoot, как показано ниже.

Содержимое белой страницы будет отображать код состояния, путь и причину ошибки, но реальная среда публикации онлайн-генерации обычно не допускает такой ситуации, и больше — это настраиваемые страницы 404 или 500 страниц.

Итак, теперь мы пришли к пониманию, в какой ситуации будут появляться белые страницы и как решить эту проблему. Давайте воспользуемся случаем 404, чтобы понять причину.

Перейти непосредственно к классу DispatcherServlet protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception Метод, содержащий фрагменты кода

В методе getHandler будет выполняться обход HandlerMapping в текущем веб-контейнере, чтобы найти соответствующий обработчик

Из приведенного выше рисунка очевидно, что текущий удобный обработчик — SimpleUrlHandlerMapping, потому что URL-адрес содержит /** , Все URL-адреса могут быть сопоставлены, Не войдет в noHandlerFound позади , Обработчик адаптации HandlerAdapter — это объект, созданный HttpRequestHandlerAdapter.

Не удается найти соответствующий ресурс в mv = ha.handle (loadedRequest, response, mappedHandler.getHandler ()), установите код состояния ответа на 404Подробнее см. Метод handleRequest класса ResourceHttpRequestHandler.

Теперь это эквивалентно установке кода состояния запроса на 404, больше ничего не делается, mv также равно null

В это время вам нужно вернуться к процессу вызова Tomcat. Если вы запрашиваете процесс вызова Tomcat, вы должны знать, что когда Tomcat получает запрос сокета Socket на соединителе, он упаковывается в запрос, ответ и другую информацию, которая будет отправлена ​​в Engine-> Host и другие компоненты. Он доставляется слой за слоем, затем принимается конвейером каждого компонента, а затем фильтруется соответствующим клапаном (клапаном) слой за слоем.

На этот раз дошел до класса StandardHostValve private void status(Request request, Response response) метод

Объедините код и диаграмму, а затем внимательно прочтите белую страницу. This application has no explicit mapping for /error , Маршрут error, причина отсюда, а затем переход вперед, адрес маршрута error

Белая страница mv, предоставляемая SpringBoot, используется позже для визуализации содержимого белой страницы, которую мы видим.

Пока что весь процесс выполнен,Подводя итог, это запрос несуществующей ссылки, которая перенаправляется в запрос / error после того, как обнаруживается, что это запрос 404.

Тогда решение очень простое, есть три решения, но эти три решения под разными углами, чтобы решить проблему.

  • Добавить перехватчик
  • Добавить ErrorPage
  • Добавить / путь ошибки

2. Решите проблему с белой страницей.

2.1, добавить перехватчик

После того, как перехватчик перехватит запрос / error, он вынужден изменить mv, так что последний отрендеренный mv для пробного использования является нашей настраиваемой настройкой, а не содержимым белой страницы, где mv самой белой страницы будет проходить Анализатор представления ContentNegotiating Обработка становится ErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration

Обратите внимание, что все это истечение фактически было обработано 3 HTTP-запросами,На следующем рисунке показана информация журнала, распечатанная с использованием мониторинга событий HTTP.

Пройдите через / abc ==> jump / err ==> jump / error (содержимое не отображается, потому что содержимое, отправленное в браузер, было отображено с помощью / err

Реальный поток обработки вызовов состоит в том, что / abc не находит подходящий обработчик, а затем решает передать его на путь / error для обработки, но он перехватывается перехватчиком и перенаправляется в / err для обработки.

Недостатки: все запросы для этого маршрута будут перехвачены, включая статические файлы ресурсов, что не оказывает большого влияния на внутренние службы, которые предоставляют чистые интерфейсы. Другие службы будут иметь влияние

2.2, добавьте ErrorPage

Добавление подходящей ErrorPage не приведет к переходу к пути по умолчанию / ошибке перехватчика, а перейдет к настраиваемой ErrorPage. Причина этого была указана в методе статуса выше.

В приведенном выше коде добавлено несколько путей перехода к странице ошибки ErrorPage и соответствующие им коды ошибок HTTP. В нашем текущем примере должен быть выполнен переход к соединению / 404, а затем как я могу получить сообщение об ошибке после его выполнения? В принципе, он должен отображать 404 Содержимое файла .html и классическая страница ошибок Tomcat отображаются одновременно, как показано на следующей странице, и содержимое вывода журнала.

Это проблема скачка петли

Когда в системе не указан преобразователь четкого представления, система будет использовать свой собственный преобразователь по умолчанию. InternalResourceView , Он проверит текущий URL-адрес перед отображением. Если обнаружится, что запрошенный URL-адрес соответствует целевому URL-адресу, он будет определен Вперед сам появляются Circular view path Эта проблема

Итак, как ее решить, нужно исходить из фундаментальной цели

  • Добавьте синтаксический анализатор шаблона, чтобы синтаксический анализатор по умолчанию не использовался
  • Изменить путь перехода

Вы можете понять конкретные решения самостоятельно.В этой статье не используется отрисовка механизма шаблонов, а непосредственно отображаются основные данные.

2.3, путь добавления / ошибки

Как вы знаете выше, поскольку система по умолчанию переходит к / error и завершает рендеринг данных, недостаточно настроить маршрут / error и избежать проблемы отсутствия статических ресурсов, но обратите внимание, что есть Один вопрос, подробности см. На рисунке ниже

Во-первых, я добавил и определил очень простой метод обработки пути ошибки, но при запуске Springboot есть 3 метода обработки пути ошибки, и они одновременно принадлежат одному и тому же дескриптору. Правила маршрутизации URL Обработка, выберите ручку в автоконфигурации,Это должно было привести к тому, что наш заказ / ошибка недействительны

После тестирования он действительно недействителен, и белая страница все еще отображается, так как это решить? Есть несколько способов сделать то же самое

    В соответствии с правилами сопоставления маршрутизации измените соответствующий контент, чтобы при окончательном выборе процессора он достиг нашего пользовательского процессора, но это очень сложно. Вам необходимо очень четко понимать правила сопоставления маршрутизации самого Spring mvc, чтобы гарантировать, что сопоставление URL-адресов Приоритетные вопросы, требующие решения, и т. Д.

Мы уже знаем, что эти три / ошибки находятся в картографе маршрутов RequestMappingHandlerMapping.Мы можем сделать так, чтобы пользовательский процессор не сохранялся в карте маршрутов, и сделать Spring приоритетом согласованного преобразователя маршрутов при опросе. Да, но на самом деле BeanNameUrlMapping в handlerMapping все еще находится после RequestMappingHandlerMapping, если вы измените порядок, это также очень сложно

EndpointHandlerMapping — это конечная точка в исполнительном модуле Springboot. Настроить конечную точку сложно, и она не подходит для текущего проекта.

Использование SimpleUrlHandlerMapping не подходит для Springboot. Если вы используете конфигурацию xml, вы можете напрямую установить ее URL-адрес. Это будет очень удобно. Если вы применяете метод аннотации в springboot, требуется дополнительная настройка, как показано в следующем коде

Хотя / error вводится в SimpleUrlHandlerMapping, он все равно будет отображаться, даже если добавлена ​​дополнительная конфигурация Нет ошибки адаптера ,Этот метод не применим

Оглядываясь назад на наблюдение BasicErrorController, мы можем унаследовать интерфейс ErrorController сами.

Источник

Spring выдает ошибку Whitelabel error page, что не так?

давай читать то, что написано вместе за ручку =)
«это приложение не имеет эксплицитного (явного) маппинга для /error, поэтому ты видишь это»
добавь какой-то любой маппинг напр
@RestController
public class MyController <

@GetMapping(«/error»)
public String smth() <
return «Error world»;
>
>
пробегись по spring boot in action. сам не читал, но говорят годная, странич всего ничего

в пропертях добавь
server.error.whitelabel.enabled=false

ну или нарисуй свою страничку error.html
закинь в resources/templates

создай свой контроллер чтоб перехватить дефолтовое поведение

@Controller
public class MyErrorController implements ErrorController <

@RequestMapping(«/error»)
public String handleError() <
//do something like logging
return «error»;
>

@Override
public String getErrorPath() <
return «/error»;
>
>

можешь под каждую свою ошибку свою error страничку сделать
типа error404.html error500.html

и переписать метод вот так

@RequestMapping(«/error»)
public String handleError(HttpServletRequest request) <
Object status = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);

if (status != null) <
Integer statusCode = Integer.valueOf(status.toString());

if(statusCode == HttpStatus.NOT_FOUND.value()) <
return «error404»;
>
else if(statusCode == HttpStatus.INTERNAL_SERVER_ERROR.value()) <
return «error500»;
>
>
return «error»;
>

тогда будет подгружать нужную тебе страничку ошибки.

но как ты уже понял. это всё лишь чтоб настроить что показывать.

почему именно у тебя ошибка происходит — это ты уж в своём аппе копайся.

Источник

Внутренняя ошибка сервера 500 в Госуслуги — как исправить

Внутренняя ошибка сервера «Госуслуги» (500) — частое явление среди активных интернет-пользователей. Частенько приносит неудобства тем, кто собирается посетить сайт Gosuslugi.ru. Эксперты отмечают всплеск таких ошибок на сайте во время активных посещений портала по различным бытовым вопросам. Часто это бывает сезонным явлением — люди записывают детей в школу или встают в очередь в поликлинику, платят по штрафам за правонарушения на дорогах, оформляют заграничные паспорта, вносят налоговые платы и т. д. В обзоре мы разберемся, что делать, если не работает сайт или личный кабинет в сервере «Госуслуги» и как устранить ошибку выполнения операции под номером 500.

Error 500: причины появления бага

Сам код свидетельствует о неправильной обработке запросов. В это же время внутренние сбои не пропускают запросы на прочтение, но при этом ПО работает правильно — такой вот парадокс.

Важно! Код 500 — внутренний, поэтому, появляясь на конкретном ресурсе и не распространяясь по всем порталам, означает, что вы ничего не измените, остается только ждать.

Есть и такой список возможных причин того, что сайт Gosuslugi выдает ошибку:

  1. Неверно прописаны скрипты cqi.
  2. Запущен DNS, VPN или же прокси-сервер.
  3. В работе находятся некоторые плагины или расширения.
  4. Скрипт в продолжительной работе.
  5. Права доступа открыты или неверные.
  6. Сбой с htaccess.
  7. Нехватка памяти для корректной работы кода.
  8. Сбой WordPress.
  9. Барахлит Joomla или другая CMS-ка.

Произошла ошибка 500: устраняем в 2 способа

У нас есть две инструкции — для обычных пользователей и для администраторов ресурсов, начнем с более простой.

Стандартное руководство для обычных пользователей

Если вы посетили сайт Gosuslugi и увидели ошибку, скорее всего, это является внутренним системным сбоем сервера и администратор наверняка уже работает над устранением сбоя.

Правда, бывают случаи, когда проблема кроется в вашем оборудовании и софте — самом ПК, браузере, интернет-подключении или каком-либо ПО. Чтобы устранить баг, попробуйте действовать так:

  • Перезагрузите web-страничку.
  • Выключите или перезалейте имеющиеся плагины и расширения в браузере.
  • Отключите оформление браузера или полностью переустановите программу. Также будет полезным софт CCleaner для чистки лишнего.
  • Смените локализацию, выбрав другое государство в настройках браузера.
  • Попробуйте зайти с использованием ВПН (или прокси, браузера Тор и т. п.).
  • Можете подергать настройки ДНС, установленные провайдером, и прогнать на зловреды онлайн-DNS, если пользуетесь таковыми.
  • Дождитесь, пока на сайте Gosuslugi проведут и завершат техработы. Кстати, у сайта государственный статус, поэтому смело можно обращаться в call-центр за помощью.
  • Зайдите с софта для Android или IOS — у ресурса есть собственное приложение, оно может работать.

На заметку! Код может отображаться только в некоторых разделах сайта или на этапе авторизации (регистрации). В этом случае вам точно нужно воспользоваться чатом с оператором, который вы найдете в нижнем углу экрана с правой стороны.

Инструкция для админов

  1. Проверьте корректность работы файла под именем error log.
  2. Попробуйте поставить права доступа на коды cgi — 0755.
  3. Если истекло время ожидания ответа от сервера, измените интервал на отрезок побольше.
  4. Используйте ПО, которое меняет права на папки. Оптимальная цифра для скриптов — 600, а у всех остальных права должны быть 644, у каталогов — 755.
  5. Что касается файла .htaccess, то из-за модификации его директивы могут быть ошибочными. Отыщите файл и переместите его или же сделайте резервную копию и снесите .htaccess.

Что еще нужно знать админу?

Полезными будут такие советы:

  • При массовом посещении сайта хостинг отследил, что некоторым скриптам требуется больше памяти, чем другим, поэтому такие аккаунты блокировались с выдачей кода 500 и внутренней ошибки. Чтобы исправить этот случай, нужно пробивать на корректность работы код, чтобы исключить сверхпотребление.
  • Простейший способ — выключение «ВордПресс». Но способ лишь на время устранит проблему, ведь, выключая WP, вы рискуете потерять часть плагинов.
  • У админов, работающих с CMS Джумла, также бывают проблемы при входе в профиль. В этом случае рекомендуется перейти в logs, где выбрать error.php для его проверки на корректность работы. Можно еще выставить права доступа — 777. А также пробуйте методом тыка выключать по очереди каждый плагин.
  • Закажите платную проверку файлов на хостинге на вирусное ПО. Часто зловреды «пожирают» часть файлов. Ну, а если и это не помогло, остается только путь в техподдержку или call-центр.

Выводы

Теперь вы знаете, что это такое — ошибка 500, и как действовать, кем бы вы ни были: обычным пользователем или продвинутым админом. Мы все же советуем ждать устранения неполадок на сайте, обычно это занимает не больше суток. А тем, у кого есть собственный ресурс, мы советуем сменить хостинг на более дорогой и проверенный, ведь невозможность посещать ресурс оборачивается потерей ваших средств, особенно если у вас интернет-магазин или серьезный портал с уверенным трафиком.

Источник

Let’s learn about the Whitelabel error page in Spring Boot and how to customize or disable them. White label error pages are default behavior from Spring Boot. Like any other feature, We can customize this feature to great extent.

What are Whitelabel error pages in Spring Boot?

Depending on API client request or browser request, spring boot provides an error JSON response or a full HTML error page. For example, let’s create a simple /hello endpoint that throws an exception always.

@RequestMapping("/hello") String hello() { throw new IntrovertException("Don't bother me please..!"); }

Code language: Java (java)
Whitelabel error page showing a generic information about an error

Even though this page looks simple, you can add details to it using the following configuration.

server.error.include-message=always server.error.include-exception=true server.error.include-stacktrace=always server.error.include-binding-errors=always

Code language: Properties (properties)
whitelabel error page with details

Even though the messages are helpful, this page may not fit well with your other page designs. So if you want to override this page with your own design, you are in luck.

Overriding Whitelabel Error Pages

Spring boot provides a /error mapping at a global servlet container level. This mapping handles requests and sends back JSON or HTML view as a response with error codes/messages. But the view that we saw above looks default. If you notice the first line of the error page, it says “This application has no explicit mapping for /error, so you are seeing this as a fallback.”

Here, the spring boot is trying to hint to you that you need to provide your own template to handle these error requests. So let’s see how to do that.

As we know, The handler mapped for /error expects a view to show the HTML response. If it doesn’t find a view matching “error” it will use the placeholder we have seen above. So we first need to add a template called error.html. But the template alone will not work. You also need to add one of the spring boot supported template engines. In our case, we are adding thymeleaf.

<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>

Code language: HTML, XML (xml)

Next, you need to add the error.html template into your src/main/resources/templates directory.

With the above in place, the following MVC attributes will be available for you to access in the templates.

  1. message – Return value of exception.getMessage()
  2. exception – A string that contains the canonical exception name.
  3. trace – The complete stacktrace of the exception that caused this error.
  4. errors – A list of validation failures that occured during the request.

Along with these, there is also a status attribute that gives the HTTP status code for the error response. With that in place, we can rewrite our template file to show all these attributes.

<!doctype html> <html lang="en"> <head> <title th:text="${message}"></title> </head> <body> <table border="1"> <tr><td>Error Message</td><td th:text="${message}"></td></tr> <tr><td>Status Code</td><td th:text="${status}"></td></tr> <tr><td>Exception</td><td th:text="${exception}"></td></tr> <tr><td>Stacktrace</td><td><pre th:text="${trace}"></pre></td></tr> <tr><td>Binding Errors</td><td th:text="${errors}"></td></tr> </table> </body> </html>

Code language: HTML, XML (xml)

This simple template will yield the following error page when we access /hello.

whitelabel page showing error details

With a little bit of CSS, we can get this page to look better and more appealing.

Custom error page with details and CSS

Disabling Whitelabel error page altogether /Tomcat whitelabel

Spring boot also provides a way to disable the Whitelabel error page altogether using server.error.whitelabel.enabled setting. When set to false, the server will show an error page specific to the servlet container(tomcat). For example, the below error page from tomcat will be visible if the Whitelabel is disabled and no error template is available.

Tomcat error page when whitelabel is disabled

You can swap tomcat with jetty and you will still see an error page like this offered by the jetty runtime. And undertow currently doesn’t provide a view. But it does send response codes.

Important things to note

Always use a custom error.html page for the following reasons.

  1. Default whitelabel page lets hackers know you are using spring boot. This means they only need to try the exploits for spring boot.
  2. Never show exceptions in your production servers. Exceptions are great info for hackers.
  3. A custom error page with proper CSS will blend in to your other pages. You can even provide links and search boxes that can redirect users back to your site.

You can hide specific error attributes based on the configuration we saw earlier. Also, all these configurations are also applicable for the JSON response as well. If your request contains Accept: application/json header, then the response will be in the form of JSON. Even here, you can access all these attributes. For example, take a look at the below request.

Here you can see the trace, exception, and message attributes being available as JSON.

Summary

To sum it up, we learned about white label error pages and how to customize them. We found out how to override the default Whitelabel with our own error.html. You can check out all these examples at our GitHub Repository.

Related

My Controller

@Controller
//@RequestMapping("/")
//@ComponentScan("com.spring")
//@EnableAutoConfiguration
public class HomeController {

    @Value("${framework.welcomeMessage}")
    private String message;

    @RequestMapping("/hello")
    String home(ModelMap model) {
        System.out.println("hittin the controller...");
        model.addAttribute("welcomeMessage", "vsdfgfgd");
        return "Hello World!";
    }

    @RequestMapping(value = "/indexPage", method = RequestMethod.GET)
    String index(ModelMap model) {
        System.out.println("hittin the index controller...");
        model.addAttribute("welcomeMessage", message);
        return "welcome";
    }

    @RequestMapping(value = "/indexPageWithModel", method = RequestMethod.GET)
    ModelAndView indexModel(ModelMap model) {
        System.out.println("hittin the indexPageWithModel controller...");
        model.addAttribute("welcomeMessage", message);
        return new ModelAndView("welcome", model);
    }
}

My JSP (welcome.jsp) inside /WEB-INF/jsp (parent folder is WebContent)

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Welcome to Spring Boot</title>
</head>

<body>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
Message: ${message}
</body>
</html>

My pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>SpringBootPlay</groupId>
    <artifactId>SpringBootPlay</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.0.RELEASE</version>
    </parent>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.1.3</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-io</artifactId>
            <version>1.3.2</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <dependency>
            <groupId>com.jcabi</groupId>
            <artifactId>jcabi-log</artifactId>
            <version>0.17</version>
        </dependency>
    </dependencies>
    <properties>
        <java.version>1.8</java.version>
        <start-class>com.spring.play.BootLoader</start-class>
        <main.basedir>${basedir}/../..</main.basedir>
        <m2eclipse.wtp.contextRoot>/</m2eclipse.wtp.contextRoot>
    </properties>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <configuration>
                    <useSystemClassLoader>false</useSystemClassLoader>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

My App Initializer

@EnableAutoConfiguration
@SpringBootApplication
@ComponentScan({ "com.spring.controller" })
@PropertySources(value = { @PropertySource("classpath:/application.properties") })
public class BootLoader extends SpringBootServletInitializer {

    final static Logger logger = Logger.getLogger(BootLoader.class);

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(BootLoader.class);
    }

    public static void main(String[] args) {
        SpringApplication.run(BootLoader.class, args);
    }
}

I even added thymeleaf dependency to my pom. It still didn’t work. When ever I hit localhost:8080/hello or /indexPage or /indexPageWithModel it always says

Whitelabel Error Page

This application has no explicit mapping for /error, so you are seeing this as a fallback.

Wed Sep 21 21:34:18 EDT 2016
There was an unexpected error (type=Not Found, status=404).
]/WEB-INF/jsp/welcome.jsp

My application.properties

spring.mvc.view.prefix: /WEB-INF/jsp/
spring.mvc.view.suffix: .jsp
framework.welcomeMessage=Welcome to Dashboard

Please help me. Thanks!

This application has no explicit mapping for /error, so you are seeing this as a fallback. error can be resolved in three ways, Identify the loading issue of the controller or method, disable the error page from the browser, and customize the error page to display the appropriate error message. There was an unexpected error Whitelabel Error page. It returns a 404 page not found error.

In this post, we will see about this error “Whitelabel Error page, This application has no explicit mapping for /error, so you are seeing this as a fallback.”. You see this error, because something went wrong in the application. For some reason, Spring boot can not server the web page

If the url invokes a rest call or a jsp call to the spring boot application, the spring boot will not be able to serve the request. Instead, the “Whitelable Error Page” page will be displayed in the browser.

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

Fri Apr 10 22:45:19 IST 2020
There was an unexpected error (type=Not Found, status=404).
No message available

How to reproduce this Whitelabel Error Page

Create a web-based spring boot application in the spring tool suite. In the pom.xml file, add spring-boot-starter-web dependency. The maven dependence will be as shown in the code below.

pom.xml

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

The spring boot main class will be created in the “com.yawintutor.application” package. The main class will be shown in the code below.

Application.java

package com.yawintutor.application;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {

	public static void main(String[] args) {
		SpringApplication.run(Application.class, args);
	}
}

A rest controller class is created to serve a rest call. The controller class “TestController.java” is created in the controller package “com.yawintutor.controller.”

TestController.java

package com.yawintutor.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {

	@RequestMapping("/welcome")
	public String welcomepage() {
		return "Welcome to Yawin Tutor";
	}

}

To reproduce this error page, run the Spring Boot Application. The spring boot application starts the tomcat server and listens to port 8080. Open a web browser, type the “http:/localhost:8080/welcome” url. The “Whitelabel error page” will be shown in the browser.

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

Root Cause

If the url invokes a rest call or a jsp call to the spring boot application, the spring boot will not be able to serve the request. There are two reasons for failing to serve the request. Either the controller class is not loaded in the spring boot context or the rest call is not available.

There are three ways to solve this problem. Identify the loading issue of the controller or method, disable the error page from the browser, and customize the error page to display the appropriate error message.

Solution 1 – Root Package

The main class “Application.java” and the controller class “TestController.java” are in packages of parallel level (com.yawintutor.application, com.yawintutor.controller). Make sure your main class is in the root package. The other classes should be in the root sub package. The spring boot application scans the package from the root package where the main class exist with annotation @SpringBootApplication and sub packages.

com
   +-- yawintutor
         +-- application
             |  +-- Application.java (Main class)
             |
             +-- controller
                 +-- TestController.java

Solution 2 – @ComponentScan

In the spring boot application, if the main class package is not a root package, the other package beans will not be loaded in the spring boot context. The @ComponentScan annotation in the main class informs the bean packages to be loaded at startup.

package com.yawintutor.application;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication
@ComponentScan({"com.yawintutor.controller"})
public class Application {

	public static void main(String[] args) {
		SpringApplication.run(Application.class, args);
	}

}

Solution 3 – Typo Error

If the main class package is a root package, still if you see the error, check the rest controller’s method signature. The rest call url and the configured request mapping url should match. Check the rest call url for any typo error. If anything exists, correct the error. Check the RequestMapping configuration in the rest controller and correct the request mapping url.

Make sure the rest call url and the request mapping url in the rest controller should match. In the example below, “/welcome” should match in both rest url and request mapping url.

http://localhost:8080/welcome
	@RequestMapping("/welcome")
	public String welcomepage() {
		return "Welcome to Yawin Tutor";
	}

Solution 4 – Disable the Error Page

The default Whitelabel Error page can be disabled with the configuration of “server.error.whitelabel.enabled” in the application.properties. This is not a valid solution as it appears as a blank page that does not transmit any information to the end user. 

Add the following line to the application.properties, restart the spring boot application. The default Whitelable error page will disappear and the blank page will be displayed.

application.properties

server.error.whitelabel.enabled=false

This can be configured using application.yml file as like below

application.yml

server:
	error:
		whitelabel:
			enabled:false

The error page can be disabled using the annotation @EnableAutoConfiguration with ErrorMvcAutoConfiguration in the main class. The code below shows how to disable using the annotation.

Application.java

package com.yawintutor.application;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration;

@SpringBootApplication
@EnableAutoConfiguration(exclude = {ErrorMvcAutoConfiguration.class})
public class Application {

	public static void main(String[] args) {
		SpringApplication.run(Application.class, args);
	}

}

Solution 5 – Customize using Thymeleaf Error Page

The another way of removing Whitelabel error page is replace with customized error page. The error page can be customized by adding a error.html file in resources/templates directory. This error page is rendered using Thymeleaf template engine if any error is occurred.

pom.xml

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-thymeleaf</artifactId>
		</dependency>

resources/templates/error.html

<html>
<body>
<center>
<h1>Error occurred</h1>
<h2>Please contact website admin</h2>
<a href="/">Home</a>
</center>
</body>
</html>

Solution 6 – Customize using ErrorController

If the error occurs, redirect the user to a custom error page showing the generic error message to intimate something that went wrong with the application, To take action, please contact the respective privileged person to resolve this problem. Create a customized error page that will overwrite the default error page as like below

ErrorHandlerController.java

package com.yawintutor.application;

import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ErrorHandlerController implements ErrorController{

	@Override
	@RequestMapping("/error")
	@ResponseBody
	public String getErrorPath() {
		return "<center><h1>Something went wrong</h1></center>";
	}
}

Summary

In this post, we saw an error on the “Whitelabel error page” error. In most cases, this error page is due to controller bean loading issue or method signature issue. If the error is in a valid scenario, the customization of the error message is preferred to show the appropriate error message to the end user.

image for 404 error

Sometimes it happens that the visitor writes incorrectly an URL or the page you created doesn’t exist anymore.

It’s important to return the correct code and if possible an explicit message to the user or to the search engine. 404 and 410 HTTP codes are used by Google search engine to remove old pages from their index. This avoids lowering the quality of your content because your server is showing empty pages or errors.

Here you can find the detail about how to remove permanently a page from Google.

How to return a HTTP 404 (Not found) or HTTP 410 (Gone) with Spring Boot?

If you are using @ResponseBody you can simply declare an exception:

throw new ResponseStatusException( 
  HttpStatus.NOT_FOUND, "the page is not found" 
); 

The NOT_FOUND enumerator returns a 404 error. From the Spring code: NOT_FOUND(404, Series.CLIENT_ERROR, "Not Found”),

By default, throwing ResponseStatusException will escalate the exception to the browser showing and non-user friendly presentation of our error message.

whitelabel error in spring

If you are on this post because of the Whitelabel Error Page deploying an Angular application … you are in the wrong post and you should go here: https://marco.dev/angular-spring-whitelabel

How can we avoid the ugly ‘Whitelabel Error Page’?

Spring Boot comes with an easy and smart solution. You can simply add a default page in your static assets with the name 404.html (or 410.html for the GONE HTTP message. Spring will automatically map the 404 error with the 404.html in the assets.

src/ 
 +- main/ 
     +- java/ 
     |   + <source code> 
     +- resources/ 
         +- public/ 
             +- error/ 
             |   +- 404.html 
             +- <other public assets> 

Here you have more details from the official Spring documentation

This path can be customized with the server.error.path Spring property (default: /error)

The whitelabel can be deactivated using properties: server.error.whitelabel.enabled=false

Custom ModelAndView

I prefer to handle the error page as View, if an exception is found in the backend I return a ModelAndView this gives me more flexibility if I want to send parameters (e.g. custom friendly message). Important is to give the HttpStatus.NOT_FOUND, for a ‘human’ user the http header is maybe not important but for search engines it’s very important and could avoid ‘damages’ to your SEO.

return new ModelAndView("not-found-page", HttpStatus.NOT_FOUND); 

browser console error

Deep dive into the ‘Whitelabel Error Page’

The properties of the Whitelabel and the error pages can be found here: ErrorProperties.java

This class defines the parameters name to customize the path of the error page and if the Whitelabel error is enabled or not.

The configuration of the Whitelabel is here in ErrorMvcAutoConfiguration.java

@Configuration(proxyBeanMethods = false) 
@ConditionalOnProperty(prefix = "server.error.whitelabel", name = "enabled", matchIfMissing = true) 
@Conditional(ErrorTemplateMissingCondition.class) 
protected static class WhitelabelErrorViewConfiguration { 
 
  private final StaticView defaultErrorView = new StaticView(); 
 
  @Bean(name = "error") 
  @ConditionalOnMissingBean(name = "error") 
  public View defaultErrorView() { 
    return this.defaultErrorView; 
  } 
 
  // If the user adds @EnableWebMvc then the bean name view resolver from 
  // WebMvcAutoConfiguration disappears, so add it back in to avoid disappointment. 
  ... 
} 

The same class contains the implementation as you can see Spring returns a StaticView in other words a Servlet Response (servlet.View):

private static class StaticView implements View 
@Override 
public void render(Map<String, ?> model, HttpServletRequest request, HttpServletResponse response) 
... 
response.setContentType(TEXT_HTML_UTF8.toString()); 
StringBuilder builder = new StringBuilder(); 
... 
builder.append("<html><body><h1>Whitelabel Error Page</h1>").append( 
"<p>This application has no explicit mapping for /error, so you are seeing this as a fallback.</p>") 
... 
response.getWriter().append(builder.toString());} 
... 

1. Introduction

When using springboot mvc , you may encounter this error:

You visit: http://localhost:8080/ , it should ok, but the browser display an error page like this:

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

2. Environments

  • SpringBoot 1.x and 2.x
  • Java 1.8+
  • Maven 3.3+

3. How to replay this error?

3.1 The project layout

I have a springboot project , just for test the springboot and mvc:
20180601_sberror2

It’s very simple.

3.2 The problem

when I run it, and visit http://localhost:8080, I got this:
20180601_sberror4

4. How to debug this problem?

Just search the keywords Whitelabel Error Page from the spring project at github , you can get to the ErrorMvcAutoConfiguration, which has this code:

	@Configuration(proxyBeanMethods = false)
	@ConditionalOnProperty(prefix = "server.error.whitelabel", name = "enabled",matchIfMissing = true) //notice this line
	@Conditional(ErrorTemplateMissingCondition.class)
	protected static class WhitelabelErrorViewConfiguration {...

Notice the @ConditionalOnProperty annotation, it means that:

  • If server.error.whitelabel.enabled is not defined,condition match
  • Else if server.error.whitelabel.enabled is true,condition match

5. How to solve this problem?

5.1 Disable whitelabel error page with property

According to the above inspection of the spring source code, the solution to hide the Whitelabel Error Page is :

In your src/main/resources/application.properties, just add this line:

server.error.whitelabel.enabled=false

5.2 Disable whitelabel error page with annotation

You can see that the WhitelabelErrorViewConfiguration class is loaded by ErrorMvcAutoConfiguration, which is a @Configuration class, so ,you can exclude it in your springboot main class like this:

@SpringBootApplication(exclude = {ErrorMvcAutoConfiguration.class})
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class,args);
    }
}

6. Summary

The WhiteLabel Error Page issue is a nightmare for newbies of springboot. After reading this article, you can find that the key point is to find why spring show this page and where the code is, and then the solution is simple.

  • Use custom static html error page to replace springboot whitelabel error page

Ситуация следующая:
Спринг начал выдавать Whitelabel Error Page.
Пробовал пересоздать контроллер и проект целиком, проблема не ушла.
Гугл подсказал, что это может быть связано с пакетами, но у меня с пакетами вроде все правильно.
В чем может быть причина?

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.6</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>demo</description>
    <properties>
        <java.version>11</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

Controller

package com.example.demo.controller;

import org.springframework.web.bind.annotation.GetMapping;

@org.springframework.stereotype.Controller
public class Controller {
    @GetMapping
    public String hello() {
        return "Hello";
    }
}

DemoApplication

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

}

By
Atul Rai |
Last Updated: October 2, 2019
Previous       Next


In this article, we will explore how to handle Whitelabel Error Page in Spring Boot application. During the development of Spring application, sometimes we face the Whitelabel Error Page and Spring Framework suggests us ‘This application has no explicit mapping for /error, so you are seeing this as a fallback‘ as shown below:

How to resolve Whitelabel Error Page in Spring Boot

P.S Tested with Spring Boot and Thymeleaf 2.1.8.RELEASE version.

We can resolve the Whitelabel Error Page error in 3 ways:

1. Custom Error Controller

By implementing the ErrorController interface provided by the Spring Framework itself and overrides its getErrorPath() method to return a custom path to call when an error occurred:

ErrorrHandlerController.java

package org.websparrow.controller;

import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ErrorrHandlerController implements ErrorController {

	@GetMapping("/error")
	public String customError() {
		return "The link you followed may be broken, or the page may have been removed.";
	}

	@Override
	public String getErrorPath() {
		return "/error";
	}
}

In the customError() method, we return the custom message. If we trigger a 404, 500, etc error now, our custom message will be displayed.

How to resolve Whitelabel Error Page in Spring Boot

2. Displaying Custom Error Page

Create a error.html page and put it into the src/main/resources/templates directory. Spring Boot’s BasicErrorController will automatically be picked it up by default.

error.html

<!DOCTYPE html>
<html>
<title>Error</title>
<body>

	<h1>Something went wrong!</h1>
	<p>The link you followed may be broken, or the page may have been removed.</p>

</body>
</html>

Since we’re using Thymeleaf template engine to display the custom error page. Add the Thymeleaf dependency in the pom.xml:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
    <version>2.1.8.RELEASE</version>
</dependency>

3. Disabling the Whitelabel Error Page

By setting the server.error.whitelabel.enabled property to false in the application.properties file, we can disable the white label error page.

application.properties

#Disable Whitelabel Error Page
server.error.whitelabel.enabled = false

Note: Add the right property matched with Spring Boot version:

Spring Boot Version >= 1.3 then use server.error.whitelabel.enabled = false

Spring Boot Version <= 1.2 then use error.whitelabel.enabled = false

We can achieve the same result by excluding the ErrorMvcAutoConfiguration class to the main class:

Main.java

@SpringBootApplication(exclude = { ErrorMvcAutoConfiguration.class })
public class Main {

	public static void main(String[] args) {
		SpringApplication.run(WhitelabelErrorPageApplication.class, args);
	}

}

References

  1. Customize the ‘whitelabel’ Error Page
  2. Custom Error Pages

0, краткое описание

Перед изучением этой заметки лучше всего иметь некоторое представление о Spring mvc и Tomcat, чтобы было удобнее понимать.Если вам нужно знать наиболее прямое решение, перетащите его вниз, чтобы увидеть образец кода.

Вводится настоящая причина появления белой страницы Springboot. Основная причина заключается в том, что нет подходящей ситуации соответствия и возникает ситуация 404. Затем перейдите к системной по умолчанию сначала ErrorPage, которая представляет собой содержимое белой страницы, а затем с трех точек зрения в соответствии с его спецификой. , 1. Перехватчик, 2. Новая страница ошибок, 3. Пользовательская маршрутизация / маршрутизация ошибок для решения проблемы, а также знакомство с преимуществами и недостатками каждого метода, включая основные причины ошибок страницы цикла и т. Д.

1. Страница ошибки Whitelabel

То, что называется страницей ошибок Whitelabel (также называемой белой страницей), является страницей описания аномального HTTP-запроса в SpringBoot, как показано ниже.

image

Содержимое белой страницы будет отображать код состояния, путь и причину ошибки, но реальная среда публикации онлайн-генерации обычно не допускает такой ситуации, и больше — это настраиваемые страницы 404 или 500 страниц.

Итак, теперь мы пришли к пониманию, в какой ситуации будут появляться белые страницы и как решить эту проблему. Давайте воспользуемся случаем 404, чтобы понять причину.

Перейти непосредственно к классу DispatcherServletprotected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws ExceptionМетод, содержащий фрагменты кода

mappedHandler = getHandler(processedRequest);
// находим подходящий обработчик запроса
if (mappedHandler == null || mappedHandler.getHandler() == null) {
         // В принципе, если вы его не найдете, введите здесь и установите код статуса ответа 404
         // Но после отладки так и не вошел сюда
    noHandlerFound(processedRequest, response);
    return;
}

В методе getHandler будет выполняться обход HandlerMapping в текущем веб-контейнере, чтобы найти соответствующий обработчик

image

image

Из приведенного выше рисунка очевидно, что текущий удобный обработчик — SimpleUrlHandlerMapping, потому что URL-адрес содержит/**, Все URL-адреса могут быть сопоставлены,Не войдет в noHandlerFound позади, Обработчик адаптации HandlerAdapter — это объект, созданный HttpRequestHandlerAdapter.

Не удается найти соответствующий ресурс в mv = ha.handle (loadedRequest, response, mappedHandler.getHandler ()), установите код состояния ответа на 404Подробнее см. Метод handleRequest класса ResourceHttpRequestHandler.

Теперь это эквивалентно установке кода состояния запроса на 404, больше ничего не делается, mv также равно null

В это время вам нужно вернуться к процессу вызова Tomcat. Если вы запрашиваете процесс вызова Tomcat, вы должны знать, что когда Tomcat получает запрос сокета Socket на соединителе, он упаковывается в запрос, ответ и другую информацию, которая будет отправлена ​​в Engine-> Host и другие компоненты. Он доставляется слой за слоем, затем принимается конвейером каждого компонента, а затем фильтруется соответствующим клапаном (клапаном) слой за слоем.

На этот раз дошел до класса StandardHostValveprivate void status(Request request, Response response)метод

private void status(Request request, Response response) {
        int statusCode = response.getStatus();
                 // Просмотр текущего кода состояния, текущий пример - 404
                 // Получить текущий контекст
        Context context = request.getContext();
        if (context == null) {
            return;
        }

        if (!response.isError()) {
                           // Текущий запрос верен
                           // это атомарный класс AtomicInteger errorState, если он больше 0, это считается ошибкой
             
            return;
        }

        ErrorPage errorPage = context.findErrorPage(statusCode);
                 // Об этом месте поговорим позже, это решение, устанавливаем страницу ошибки
        if (errorPage == null) {
            // Look for a default error page
            errorPage = context.findErrorPage(0);
        }
        if (errorPage != null && response.isErrorReportRequired()) {
            ...

image

Объедините код и диаграмму, а затем внимательно прочтите белую страницу.This application has no explicit mapping for /error, Маршрут error, причина отсюда, а затем переход вперед, адрес маршрута error

image

Белая страница mv, предоставляемая SpringBoot, используется позже для визуализации содержимого белой страницы, которую мы видим.

Пока что весь процесс выполнен,Подводя итог, это запрос несуществующей ссылки, которая перенаправляется в запрос / error после того, как обнаруживается, что это запрос 404.

Тогда решение очень простое, есть три решения, но эти три решения под разными углами, чтобы решить проблему.

  • Добавить перехватчик
  • Добавить ErrorPage
  • Добавить / путь ошибки

2. Решите проблему с белой страницей.

2.1, добавить перехватчик

public class CustomHandlerInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
            Object handler) throws Exception {
                         // Должно быть истиной, иначе перехватчик не сработает
                         // Конечно, вы можете перехватывать любые URL-адреса по желанию
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
            ModelAndView modelAndView) throws Exception {
            if (modelAndView != null) {
                             // Предотвращаем нулевые указатели
                             // Если это страница с ошибкой в ​​springboot, определенно не будет отображаться, что mv имеет значение null
              modelAndView.setViewName("/err");
                             // Примечание: этот запрос является всего лишь пробным и не имеет практического значения
           }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
            Object handler, Exception ex) throws Exception {
    }
}

@Bean
public WebMvcConfigurerAdapter customMvcConfigurerAdapter (){
    return new WebMvcConfigurerAdapter() {
        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            registry.addInterceptor(new CustomHandlerInterceptor()).addPathPatterns("/**");
                         // добавляем перехватчик
            super.addInterceptors(registry);
        }
    };
}

После того, как перехватчик перехватит запрос / error, он вынужден изменить mv, так что последний отрендеренный mv для пробного использования является нашей настраиваемой настройкой, а не содержимым белой страницы, где mv самой белой страницы будет проходитьАнализатор представления ContentNegotiatingОбработка становитсяErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration

Обратите внимание, что все это истечение фактически было обработано 3 HTTP-запросами,На следующем рисунке показана информация журнала, распечатанная с использованием мониторинга событий HTTP.

image

Пройдите через / abc ==> jump / err ==> jump / error (содержимое не отображается, потому что содержимое, отправленное в браузер, было отображено с помощью / err

Реальный поток обработки вызовов состоит в том, что / abc не находит подходящий обработчик, а затем решает передать его на путь / error для обработки, но он перехватывается перехватчиком и перенаправляется в / err для обработки.

Недостатки: все запросы для этого маршрута будут перехвачены, включая статические файлы ресурсов, что не оказывает большого влияния на внутренние службы, которые предоставляют чистые интерфейсы. Другие службы будут иметь влияние

2.2, добавьте ErrorPage

Добавление подходящей ErrorPage не приведет к переходу к пути по умолчанию / ошибке перехватчика, а перейдет к настраиваемой ErrorPage. Причина этого была указана в методе статуса выше.

@Bean
public EmbeddedServletContainerCustomizer containerCustomizer() {
    return new EmbeddedServletContainerCustomizer() {
        @Override
        public void customize(ConfigurableEmbeddedServletContainer configurableEmbeddedServletContainer) {
            ErrorPage errorPage400 = new ErrorPage(HttpStatus.BAD_REQUEST,"/400");
            ErrorPage errorPage404 = new ErrorPage(HttpStatus.NOT_FOUND,"/404");
            ErrorPage errorPage500 = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR,"/500");
            configurableEmbeddedServletContainer.addErrorPages(errorPage400,errorPage404,errorPage500);
        }
    };
}

 // ======= разделительная линия

 @ApiOperation («запрос 404»)
@GetMapping("404")
public String e404() {
    return "404";
}

В приведенном выше коде добавлено несколько путей перехода к странице ошибки ErrorPage и соответствующие им коды ошибок HTTP. В нашем текущем примере должен быть выполнен переход к соединению / 404, а затем как я могу получить сообщение об ошибке после его выполнения? В принципе, он должен отображать 404 Содержимое файла .html и классическая страница ошибок Tomcat отображаются одновременно, как показано на следующей странице, и содержимое вывода журнала.

image

image

Это проблема скачка петли

Когда в системе не указан преобразователь четкого представления, система будет использовать свой собственный преобразователь по умолчанию.InternalResourceView, Он проверит текущий URL-адрес перед отображением. Если обнаружится, что запрошенный URL-адрес соответствует целевому URL-адресу, он будет определенВперед сампоявляютсяCircular view pathЭта проблема

protected String prepareForRendering(HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    String path = getUrl();
    if (this.preventDispatchLoop) {
        String uri = request.getRequestURI();
        if (path.startsWith("/") ? uri.equals(path) : uri.equals(StringUtils.applyRelativePath(uri, path))) {
            throw new ServletException("Circular view path [" + path + "]: would dispatch back " +
                    "to the current handler URL [" + uri + "] again. Check your ViewResolver setup! " +
                    "(Hint: This may be the result of an unspecified view, due to default view name generation.)");
        }
    }
    return path;
}

Итак, как ее решить, нужно исходить из фундаментальной цели

  • Добавьте синтаксический анализатор шаблона, чтобы синтаксический анализатор по умолчанию не использовался
  • Изменить путь перехода

Вы можете понять конкретные решения самостоятельно.В этой статье не используется отрисовка механизма шаблонов, а непосредственно отображаются основные данные.

@RequestMapping("/")
@RestController
public class ErrorController {

         @ApiOperation («запрос 404»)
    @GetMapping("404")
    public String e404() {
        System.out.println("404............");
                 return "Это действительно страница 404, посмотрите на нее";
    }

image

2.3, путь добавления / ошибки

Как вы знаете выше, поскольку система по умолчанию переходит к / error и завершает рендеринг данных, недостаточно настроить маршрут / error и избежать проблемы отсутствия статических ресурсов, но обратите внимание, что есть Один вопрос, подробности см. На рисунке ниже

image

image

Во-первых, я добавил и определил очень простой метод обработки пути ошибки, но при запуске Springboot есть 3 метода обработки пути ошибки, и они одновременно принадлежат одному и тому же дескриптору.Правила маршрутизации URLОбработка, выберите ручку в автоконфигурации,Это должно было привести к тому, что наш заказ / ошибка недействительны

image

После тестирования он действительно недействителен, и белая страница все еще отображается, так как это решить? Есть несколько способов сделать то же самое

  • В соответствии с правилами сопоставления маршрутизации измените соответствующий контент, чтобы при окончательном выборе процессора он достиг нашего пользовательского процессора, но это очень сложно. Вам необходимо очень четко понимать правила сопоставления маршрутизации самого Spring mvc, чтобы гарантировать, что сопоставление URL-адресов Приоритетные вопросы, требующие решения, и т. Д.
  • Мы уже знаем, что эти три / ошибки находятся в картографе маршрутов RequestMappingHandlerMapping.Мы можем сделать так, чтобы пользовательский процессор не сохранялся в карте маршрутов, и сделать Spring приоритетом согласованного преобразователя маршрутов при опросе. Да, но на самом деле BeanNameUrlMapping в handlerMapping все еще находится после RequestMappingHandlerMapping, если вы измените порядок, это также очень сложно

     

    image

EndpointHandlerMapping — это конечная точка в исполнительном модуле Springboot. Настроить конечную точку сложно, и она не подходит для текущего проекта.

Использование SimpleUrlHandlerMapping не подходит для Springboot. Если вы используете конфигурацию xml, вы можете напрямую установить ее URL-адрес. Это будет очень удобно. Если вы применяете метод аннотации в springboot, требуется дополнительная настройка, как показано в следующем коде

@RequestMapping("/")
@Controller
public class SimpleUrlController {

    private static final String ERROR_PATH = "/error";

    @Resource
    private SimpleUrlHandlerMapping simpleUrlHandlerMapping;

    @PostConstruct
    public void init() {
        Map<String, Object> map = new HashMap<>();
        map.put(ERROR_PATH, this);
        simpleUrlHandlerMapping.setUrlMap(map);

        simpleUrlHandlerMapping.initApplicationContext();
                 // Вызываем отображение simpleurl
    }

    @GetMapping("/error")
    @ResponseBody
    public String error(HttpServletRequest request) {
        System.out.println("SimpleUrlController");
        Enumeration<String> attributes = request.getAttributeNames();

        Map<String, Object> map = new HashMap<String, Object>();
        while (attributes.hasMoreElements()) {
           String name = attributes.nextElement();
           if (name.startsWith("java")) {
                               // Помните, что свойства самой пружины не должны быть выставлены снаружи!
               Object value = request.getAttribute(name);
               map.put(name, value);
           }
        }
        return JSON.toJSONString(map);
    }
}

image

Хотя / error вводится в SimpleUrlHandlerMapping, он все равно будет отображаться, даже если добавлена ​​дополнительная конфигурацияНет ошибки адаптераЭтот метод не применим

Оглядываясь назад на наблюдение BasicErrorController, мы можем унаследовать интерфейс ErrorController сами.

@RequestMapping("")
@Controller
public class CustomErrorController implements ErrorController {

    private static final String ERROR_PATH = "/error";

    @GetMapping(ERROR_PATH)
    @ResponseBody
    public String error(HttpServletRequest request) {
        System.out.println("CustomErrorController");
        Enumeration<String> attributes = request.getAttributeNames();

        Map<String, Object> map = new HashMap<String, Object>();
        while (attributes.hasMoreElements()) {
           String name = attributes.nextElement();
           if (name.startsWith("java")) {
                               // Помните, что свойства самой пружины не должны подвергаться воздействию извне!
               Object value = request.getAttribute(name);
               map.put(name, value);
           }
        }
        return JSON.toJSONString(map);
    }

    @Override
    public String getErrorPath() {
        return ERROR_PATH;
    }
}

Понравилась статья? Поделить с друзьями:
  • Что означает card error
  • Что означает warning lnb short на телевизоре как это исправить
  • Что означает authentication error
  • Что означает ussd error на телефоне
  • Что означает an unknown error occurred