Explicit mapping for error so you are seeing this as a fallback

Whitelabel Error Page This application has no explicit mapping for /error, so you are seeing this as a fallback. There was an unexpected error No message available

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.

directory
I. Error Prompt:
Ii. Reasons:
Iii. Solution 1: Package of the mobile control layer:
4. Solution 2: Add @SpringBootApplication(scanBasePackages=” Controller “)
5. Summarize the reasons for possible errors:
Reason 1:
Reason 2:
Reason 3:
Vi. Cause of Error of Eclipse starting Springboot:


An error was reported when Springboot was running, other configurations were fine, and after a long look I found the cause.
I. Error Prompt:

Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Mon Jun 24 14:56:23 CST 2019
There was an unexpected error (type=Not Found, status=404).
No message available

Ii. Reasons:
Problem with IDEA directory structure, the location of the Application startup class is wrong. To place the Application class on the outermost side, it contains all the subpackages. And my Controller is in the outermost package. The page could not be found.

Iii. Solution 1: Package of the mobile control layer:
Move the Controller class in, and it will run successfully.

Refresh again and the page will open successfully.

4. Solution 2: Add @SpringBootApplication(scanBasePackages=” Controller “)
In your Demo01Application class that you started, add a comment specifying the location of your Controller, and you can specify the load and solve the problem successfully.

package com.hh.demo01;

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

@SpringBootApplication(scanBasePackages="controller")
public class Demo01Application {

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

}

5. Summarize the reasons for possible errors:
This exception indicates that the url for the jump page has no corresponding value.
Reason 1:
The Application startup class is not in the right place. To place the Application class on the outermost side, it contains all subpackages
reason :spring-boot automatically loads all components under the package where the startup class is located and under its subpackages.
Reason 2:
In springboot configuration file: application. Yml or application. The properties on the view of the parser configuration problem:
when the spring under the pom file – the boot – starter – paren version used when high:
spring. MVC. The prefix/spring. MVC. The suffix
As spring under the pom file – the boot – starter – paren version low when use:
spring. The prefix/spring. The suffix
Reason 3:
Controller URL path writing problem
@RequestMapping(” XXXXXXXXXXXXXX “)
actual access path and “XXX” does not conform.
Refer to the article: https://www.cnblogs.com/lilinzhiyu/p/7921890.html

Vi. Cause of Error of Eclipse starting Springboot:
When the eclipse deployed project is launched, This application has no explicit mapping for /error, so you are seeing This as a fallback. At the same time, his log shows port 8080 being started.

And my configuration file has configured the port:

Later, it turned out that it was also because of the location of the package, that is, the above reason 1: the location of the Application startup class is wrong. To place the Application class on the outermost side, you include all subpackages because Spring-Boot automatically loads all components under the package where the startup class is located and under its subpackages.
After changing the position, it starts successfully, and the port is correct and the page is opened correctly.


Personal Summary:
I’m going to have to do some careful checking.

Read More:

The “this application has no explicit mapping for /error” view is a common Spring Boot-related issue. If you are new to Spring Boot, you might have seen this error already. If you are looking for how to solve this issue, This is what you should do.

What and why?

You would usually see this error in a Whitelabel Error Page on a browser session. For example, take a look at the following screenshot.

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

One would usually see such errors when there is an error response for the request. In this case, the server cannot find the requested URL (HTTP 404). But the reason why the error message also involves an explicit mapping for /error is due to how the Whitelabel Error page works.

Basically, Spring Boot application has an ErrorMvcAutoConfiguration for handing controller errors. For this,

  • Spring Boot creates a BasicErrorController which can handle each exceptions
  • And also, it creates a static “/error” view which is the “Whitelabel Error Page”

In other words, Spring Boot wants you to provide your own whitelabel view.

Solutions

The solution for this error is to provide a /error mapping. And you can do that in two ways.

Solution 1: Implement the ErrorController interface

You could provide your own implementation of ErrorController. For example, the below controller will show a static error message instead of a whitelabel page.

@Controller public class CustomErrorController implements ErrorController { @RequestMapping("/error") @ResponseBody String error(HttpServletRequest request) { return "<h1>Error occurred</h1>"; } @Override public String getErrorPath() { return "/error"; } }

Code language: PHP (php)

This way you are providing a mapping for /error as well as a static HTML as a response. Take a look at BasicErrorController if you want to make this response a bit more dynamic.

Solution 2: Provide an MVC template for /error

This approach is probably the best way to handle the ” no explicit mapping for /error ” message. If you are using a templating engine like Thymeleaf, you could simply provide an error.html.

As the MVC views have access to the exceptions and error messages, it is easier to define a template and let the templating engine do the rendering for you. To achieve this, make sure you have a templating engine in place. For this example, I’m using Thymeleaf. You could however use any template engine of your choice. We have a great comparison of template engines in Spring Boot if you need help deciding.

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

Code language: HTML, XML (xml)

Then create “error.html” under “src/main/resources/templates/” with the following content or similar.

<!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)

For the sake of showing more details, I have added the following two values to the application.properties.

server.error.include-exception=true server.error.include-stacktrace=always

Code language: PHP (php)

Result of a custom /error mapping

With some CSS magic, you could get a nice error page for yourself.

custom error.html with CSS

Summary

To conclude, we learned why “This application has no explicit mapping for error” message appears and how to solve them in two different ways.

Related

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement. We’ll occasionally send you account related emails.

Already on GitHub?
Sign in
to your account

Comments

@nitinpawar283

@wilkinsona

Given the lack of description, I’m guessing this was opened in error.

Whitelabel Error Page This application has no explicit mapping for /error, so you are seeing this as a fallback. Wed May 31 23:17:56 IST 2017 There was an unexpected error (type=Not Found, status=404).

This is the default content of a 404 response when a page isn’t found for the request’s URL.

@sassoura

This comment has been minimized.

@varun-vijayarao

This comment has been minimized.

@snicoll

This comment has been minimized.

@ghost

This comment has been minimized.

@kvh44

I have found the problem. When you execute the generated jar file of spring boot. You need to execute the command out of the folder target like this

» mvn clean package && java -jar target/mmm-0.0.1-SNAPSHOT.jar».

Otherwise it can’t find the folder WEB-INF which located in «/src/main/webapp/».

@wilkinsona

@kvh44 Thanks for trying to help, but if you are building a jar file you shouldn’t be using src/main/webapp. There’s a note about this in the documentation:

Do not use the src/main/webapp directory if your application is packaged as a jar. Although this directory is a common standard, it works only with war packaging, and it is silently ignored by most build tools if you generate a jar.

@BynuLorenz

@kvh44 Thank you for your solution. took me days to figure it out. Any suggetion why application can’t find WEB-INF which located in «/src/main/webapp/» while running on IDE.

@davidecherubini

@kvh44 I’m new to programming and I encountered the same problem mentioned above, when I run the application via SpringBoot.
Where should I write that line out of the destination?

@jmdopereiro

@ghost
ghost

mentioned this issue

Jan 20, 2021

@Alpiniatechnologies

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

Wed Aug 04 21:50:06 IST 2021
There was an unexpected error (type=Not Found, status=404).

this my error
please solve

@snicoll

давай читать то, что написано вместе за ручку =)
«это приложение не имеет эксплицитного (явного) маппинга для /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»;
>

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

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

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

В этом приложении нет явного сопоставления для / error

Я использовал maven для создания учебника https://spring.io/guides/gs/uploading-files/
Все используемые мной коды были скопированы.

Приложение может работать, но я получаю сообщение об ошибке:

Whitelabel Error Page This application has no explicit mapping for /error, so you are seeing this as a fallback. Tue Jun 30 17:24:02 CST 2015 There was an unexpected error (type=Not Found, status=404). No message available

Как я могу это исправить?

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

Когда вы запускаете приложение Spring Boot (т. Е. Класс, помеченный @SpringBootApplication), Spring будет сканировать только классы, расположенные ниже вашего основного пакета классов.

Когда мы создаем загрузочное приложение Spring, мы аннотируем его @SpringBootApplication аннотациями. Эта аннотация «завершает» многие другие аннотации, необходимые для работы приложения. Одна из таких аннотаций — @ComponentScan аннотация. Эта аннотация сообщает Spring искать компоненты Spring и настраивать приложение для запуска.

Класс вашего приложения должен быть на вершине иерархии пакетов, чтобы Spring мог сканировать подпакеты и находить другие необходимые компоненты.

Ниже фрагмент кода работает, поскольку пакет контроллера находится в com.test.spring.boot пакете

Ниже фрагмент кода НЕ работает, поскольку пакет контроллера НЕ находится в com.test.spring.boot пакете

Из документации Spring Boot:

Many Spring Boot developers always have their main class annotated with @Configuration , @EnableAutoConfiguration and @ComponentScan . Since these annotations are so frequently used together (especially if you follow the best practices above), Spring Boot provides a convenient @SpringBootApplication alternative.

The @SpringBootApplication annotation is equivalent to using @Configuration , @EnableAutoConfiguration and @ComponentScan with their default attributes

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

Контроллер ошибок в моем приложении выглядит так:

Вышеупомянутый класс основан на классе Springs BasicErrorController .

Вы можете создать экземпляр вышеуказанного ErrorController в @Configuration файле следующим образом:

Вы можете переопределить значение ErrorAttributes по умолчанию , реализовав ErrorAttributes . Но в большинстве случаев атрибутов DefaultErrorAttributes должно быть достаточно.

В моем случае класс контроллера был аннотирован @Controller . Изменив это, чтобы @RestController решить проблему. В основном @RestController это @Controller + @ResponseBody так либо использовать @RestController , либо @Controller с @ResponseBody аннотацией к каждому методу.

в моем случае это из-за позиции пакета, то есть пакет контроллера должен быть выше пакета основного класса

если мой пакет основного класса — это package co.companyname.spring.tutorial; любой пакет контроллера, package co.companyname.spring.tutorial.WHAT_EVER_HERE;

после завершения кодирования нажмите кнопку загрузки приборной панели

введите описание изображения здесь

последнее, что нужно, чтобы убедиться, что ваш контроллер отображает или не только консоль, вы должны увидеть что-то smilliar

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

Попробуйте добавить зависимость.

По умолчанию весенняя загрузка будет сканировать текущий пакет на предмет определения bean-компонента. Поэтому, если ваш текущий пакет, в котором определен основной класс, а пакет контроллера не совпадает, или пакет контроллера не является дочерним пакетом вашего основного пакета приложения, он не будет сканировать контроллер. Чтобы решить эту проблему, можно включить список пакетов для определения bean-компонента в основной пакет.

или создать иерархию пакетов, в которой дочерний пакет является производным от основного пакета

Я разрабатываю приложение Spring Boot в течение нескольких недель .. И я получил ту же ошибку, что и ниже;

Whitelabel Error Page This application has no explicit mapping for /error, so you are seeing this as a fallback. Thu Jan 18 14:12:11 AST 2018 There was an unexpected error (type=Not Found, status=404). No message available

Когда я получаю это сообщение об ошибке, я понял, что мой контроллер или класс контроллера отдыха не определен в моем проекте. Я имею в виду, что все наши пакеты контроллеров не являются одним и тем же пакетом с основным классом, который включает аннотацию @SpringBootApplication .. Я имею в виду, что вам нужно добавить имя вашего пакета контроллера в аннотацию @ComponentScan к вашему основному классу, который включает аннотацию @SpringBootApplication. Если вы напишете приведенные ниже коды, ваша проблема будет решена . Самое главное, вы должны добавить весь пакет вашего контроллера в аннотацию @ComponentScan, как я сделал в приведенном ниже

Я надеюсь, что эти коды помогут кому-то .

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

Проблемы с простым проектом с Spring Framework

Пытаюсь написать приложение по https://www.toptal.com/spring/beginners-guide-to-mvc-with-spring-framework Запускается успешно, но на localhost пишет:

Whitelabel Error Page

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

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

В HTML в строке по типу

выделяется как ошибка. Почему?

При работе Spring Boot + Freemarker если появляется страница:

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

В версии spring-boot-starter-parent 2.2.1.RELEASE не работает freemarker :

    переименуйте файлы Freemarker c .ftl на .ftlh

Добавьте в application.properties :

spring.freemarker.expose-request-attributes=true
spring.freemarker.suffix= .ftl

Проблема #1: на / ничего не замаплено, поэтому при открытии сайта вы видите подобную ошибку.

Проблема #2: если обратиться по адресу /students , то появляется еще одна ошибка, но уже другая: Exception evaluating SpringEL expression: «student.forename + ‘ ‘ + student.surame» (students:16) . Если очень внимательно посмотреть, то уже ясно в чем дело, но на всякий случай можно посмотреть в консоль на исключение: org.springframework.expression.spel.SpelEvaluationException: EL1008E:(pos 33): Property or field ‘surame’ cannot be found on object of type ‘wenti.entity.Student’ — maybe not public? Причина в банальной опечатке — вы обращаетесь к полю surame , вместо surname .

В ошибке написано, что неверный мапинг по адресу /error . Spring перенаправляет вас на страницу /error когда по вашему GET запросу произошла ошибка на сервере.

Какие есть варианты 1. Ошибка при получении/обработке данных на сервере (как пример NullPointerException ). Пройтись дебагом по коду, посмотреть не выпадает ли где exception. 2. Ошибка при парсинге страницы thymeleaf.

Посмотрите лог, скорее всего ваша ошибка выше, чем то, что вы указали в отрывке.

user avatar

В дополнение к ответу о том, что:

При работе Spring Boot + Freemarker если появляется страница:

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

У меня версия spring-boot-starter-parent 2.5.3 чтобы работал freemarker сделал следующее:

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

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

Содержание

  1. Русские Блоги
  2. Основная причина страницы ошибки SpringBoot Whitelabel, три решения и их характеристики
  3. 0, краткое описание
  4. 1. Страница ошибки Whitelabel
  5. 2. Решите проблему с белой страницей.
  6. Whitelabel error page что это за ошибка
  7. Spring выдает ошибку Whitelabel error page, что не так?
  8. В этом приложении нет явного сопоставления для / error
  9. Проблемы с простым проектом с Spring Framework

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

Основная причина страницы ошибки 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 сами.

Источник

Whitelabel error page что это за ошибка

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»;
>

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

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

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

В этом приложении нет явного сопоставления для / error

Я использовал maven для создания учебника https://spring.io/guides/gs/uploading-files/
Все используемые мной коды были скопированы.

Приложение может работать, но я получаю сообщение об ошибке:

Whitelabel Error Page This application has no explicit mapping for /error, so you are seeing this as a fallback. Tue Jun 30 17:24:02 CST 2015 There was an unexpected error (type=Not Found, status=404). No message available

Как я могу это исправить?

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

Когда вы запускаете приложение Spring Boot (т. Е. Класс, помеченный @SpringBootApplication), Spring будет сканировать только классы, расположенные ниже вашего основного пакета классов.

Когда мы создаем загрузочное приложение Spring, мы аннотируем его @SpringBootApplication аннотациями. Эта аннотация «завершает» многие другие аннотации, необходимые для работы приложения. Одна из таких аннотаций — @ComponentScan аннотация. Эта аннотация сообщает Spring искать компоненты Spring и настраивать приложение для запуска.

Класс вашего приложения должен быть на вершине иерархии пакетов, чтобы Spring мог сканировать подпакеты и находить другие необходимые компоненты.

Ниже фрагмент кода работает, поскольку пакет контроллера находится в com.test.spring.boot пакете

Ниже фрагмент кода НЕ работает, поскольку пакет контроллера НЕ находится в com.test.spring.boot пакете

Из документации Spring Boot:

Many Spring Boot developers always have their main class annotated with @Configuration , @EnableAutoConfiguration and @ComponentScan . Since these annotations are so frequently used together (especially if you follow the best practices above), Spring Boot provides a convenient @SpringBootApplication alternative.

The @SpringBootApplication annotation is equivalent to using @Configuration , @EnableAutoConfiguration and @ComponentScan with their default attributes

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

Контроллер ошибок в моем приложении выглядит так:

Вышеупомянутый класс основан на классе Springs BasicErrorController .

Вы можете создать экземпляр вышеуказанного ErrorController в @Configuration файле следующим образом:

Вы можете переопределить значение ErrorAttributes по умолчанию , реализовав ErrorAttributes . Но в большинстве случаев атрибутов DefaultErrorAttributes должно быть достаточно.

В моем случае класс контроллера был аннотирован @Controller . Изменив это, чтобы @RestController решить проблему. В основном @RestController это @Controller + @ResponseBody так либо использовать @RestController , либо @Controller с @ResponseBody аннотацией к каждому методу.

в моем случае это из-за позиции пакета, то есть пакет контроллера должен быть выше пакета основного класса

если мой пакет основного класса — это package co.companyname.spring.tutorial; любой пакет контроллера, package co.companyname.spring.tutorial.WHAT_EVER_HERE;

после завершения кодирования нажмите кнопку загрузки приборной панели

последнее, что нужно, чтобы убедиться, что ваш контроллер отображает или не только консоль, вы должны увидеть что-то smilliar

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

Попробуйте добавить зависимость.

По умолчанию весенняя загрузка будет сканировать текущий пакет на предмет определения bean-компонента. Поэтому, если ваш текущий пакет, в котором определен основной класс, а пакет контроллера не совпадает, или пакет контроллера не является дочерним пакетом вашего основного пакета приложения, он не будет сканировать контроллер. Чтобы решить эту проблему, можно включить список пакетов для определения bean-компонента в основной пакет.

или создать иерархию пакетов, в которой дочерний пакет является производным от основного пакета

Я разрабатываю приложение Spring Boot в течение нескольких недель .. И я получил ту же ошибку, что и ниже;

Whitelabel Error Page This application has no explicit mapping for /error, so you are seeing this as a fallback. Thu Jan 18 14:12:11 AST 2018 There was an unexpected error (type=Not Found, status=404). No message available

Когда я получаю это сообщение об ошибке, я понял, что мой контроллер или класс контроллера отдыха не определен в моем проекте. Я имею в виду, что все наши пакеты контроллеров не являются одним и тем же пакетом с основным классом, который включает аннотацию @SpringBootApplication .. Я имею в виду, что вам нужно добавить имя вашего пакета контроллера в аннотацию @ComponentScan к вашему основному классу, который включает аннотацию @SpringBootApplication. Если вы напишете приведенные ниже коды, ваша проблема будет решена . Самое главное, вы должны добавить весь пакет вашего контроллера в аннотацию @ComponentScan, как я сделал в приведенном ниже

Я надеюсь, что эти коды помогут кому-то .

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

Проблемы с простым проектом с Spring Framework

Пытаюсь написать приложение по https://www.toptal.com/spring/beginners-guide-to-mvc-with-spring-framework Запускается успешно, но на localhost пишет:

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

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

В HTML в строке по типу

выделяется как ошибка. Почему?

При работе Spring Boot + Freemarker если появляется страница:

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

В версии spring-boot-starter-parent 2.2.1.RELEASE не работает freemarker :

    переименуйте файлы Freemarker c .ftl на .ftlh

Добавьте в application.properties :

spring.freemarker.expose-request-attributes=true
spring.freemarker.suffix= .ftl

Проблема #1: на / ничего не замаплено, поэтому при открытии сайта вы видите подобную ошибку.

Проблема #2: если обратиться по адресу /students , то появляется еще одна ошибка, но уже другая: Exception evaluating SpringEL expression: «student.forename + ‘ ‘ + student.surame» (students:16) . Если очень внимательно посмотреть, то уже ясно в чем дело, но на всякий случай можно посмотреть в консоль на исключение: org.springframework.expression.spel.SpelEvaluationException: EL1008E:(pos 33): Property or field ‘surame’ cannot be found on object of type ‘wenti.entity.Student’ — maybe not public? Причина в банальной опечатке — вы обращаетесь к полю surame , вместо surname .

В ошибке написано, что неверный мапинг по адресу /error . Spring перенаправляет вас на страницу /error когда по вашему GET запросу произошла ошибка на сервере.

Какие есть варианты 1. Ошибка при получении/обработке данных на сервере (как пример NullPointerException ). Пройтись дебагом по коду, посмотреть не выпадает ли где exception. 2. Ошибка при парсинге страницы thymeleaf.

Посмотрите лог, скорее всего ваша ошибка выше, чем то, что вы указали в отрывке.

В дополнение к ответу о том, что:

При работе Spring Boot + Freemarker если появляется страница:

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

У меня версия spring-boot-starter-parent 2.5.3 чтобы работал freemarker сделал следующее:

Источник

Понравилась статья? Поделить с друзьями:
  • Expecting trusted certificate error
  • Expected unqualified id before token как исправить
  • Expected unqualified id before numeric constant ардуино ошибка
  • Expected the promise rejection reason to be an error
  • Expected string or bytes like object python ошибка