This application has no configured error view so you are seeing this as a fallback

I used maven to do the tutorial https://spring.io/guides/gs/uploading-files/ All the codes I used was copied. The Application can run, but I get the error: Whitelabel Error Page This applicatio...

Make sure that your main class is in a root package above other classes.

When you run a Spring Boot Application, (i.e. a class annotated with @SpringBootApplication), Spring will only scan the classes below your main class package.

com
   +- APP
         +- Application.java  <--- your main class should be here, above your controller classes
         |
         +- model
         |   +- user.java
         +- controller
             +- UserController.java

m00am's user avatar

m00am

5,67211 gold badges55 silver badges67 bronze badges

answered Aug 18, 2016 at 12:07

vignesh Subash's user avatar

vignesh Subashvignesh Subash

2,4971 gold badge10 silver badges15 bronze badges

11

When we create a Spring boot application we annotate it with @SpringBootApplication annotation. This annotation ‘wraps up’ many other necessary annotations for the application to work. One such annotation is @ComponentScan annotation. This annotation tells Spring to look for Spring components and configure the application to run.

Your application class needs to be top of your package hierarchy, so that Spring can scan sub-packages and find out the other required components.

package com.test.spring.boot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

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

Below code snippet works as the controller package is under com.test.spring.boot package

package com.test.spring.boot.controller;

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

@RestController
public class HomeController {

    @RequestMapping("/")
    public String home(){
        return "Hello World!";
    }
}

Below code snippet does NOT Work as the controller package is NOT under com.test.spring.boot package

package com.test.controller;

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

@RestController
public class HomeController {

     @RequestMapping("/")
     public String home(){
         return "Hello World!";
     }
 }

From Spring Boot documentation:

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

answered Jan 19, 2017 at 19:18

Somnath Musib's user avatar

Somnath MusibSomnath Musib

3,4403 gold badges32 silver badges46 bronze badges

0

You can solve this by adding an ErrorController in your application. You can have the error controller return a view that you need.

Error Controller in my application looks like below:

import org.springframework.boot.autoconfigure.web.ErrorAttributes;
import org.springframework.boot.autoconfigure.web.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * Basic Controller which is called for unhandled errors
 */
@Controller
public class AppErrorController implements ErrorController{

    /**
     * Error Attributes in the Application
     */
    private ErrorAttributes errorAttributes;

    private final static String ERROR_PATH = "/error";

    /**
     * Controller for the Error Controller
     * @param errorAttributes
     */
    public AppErrorController(ErrorAttributes errorAttributes) {
        this.errorAttributes = errorAttributes;
    }

    /**
     * Supports the HTML Error View
     * @param request
     * @return
     */
    @RequestMapping(value = ERROR_PATH, produces = "text/html")
    public ModelAndView errorHtml(HttpServletRequest request) {
        return new ModelAndView("/errors/error", getErrorAttributes(request, false));
    }

    /**
     * Supports other formats like JSON, XML
     * @param request
     * @return
     */
    @RequestMapping(value = ERROR_PATH)
    @ResponseBody
    public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
        Map<String, Object> body = getErrorAttributes(request, getTraceParameter(request));
        HttpStatus status = getStatus(request);
        return new ResponseEntity<Map<String, Object>>(body, status);
    }

    /**
     * Returns the path of the error page.
     *
     * @return the error path
     */
    @Override
    public String getErrorPath() {
        return ERROR_PATH;
    }


    private boolean getTraceParameter(HttpServletRequest request) {
        String parameter = request.getParameter("trace");
        if (parameter == null) {
            return false;
        }
        return !"false".equals(parameter.toLowerCase());
    }

    private Map<String, Object> getErrorAttributes(HttpServletRequest request,
                                                   boolean includeStackTrace) {
        RequestAttributes requestAttributes = new ServletRequestAttributes(request);
        return this.errorAttributes.getErrorAttributes(requestAttributes,
                includeStackTrace);
    }

    private HttpStatus getStatus(HttpServletRequest request) {
        Integer statusCode = (Integer) request
                .getAttribute("javax.servlet.error.status_code");
        if (statusCode != null) {
            try {
                return HttpStatus.valueOf(statusCode);
            }
            catch (Exception ex) {
            }
        }
        return HttpStatus.INTERNAL_SERVER_ERROR;
    }
}

The above class is based on Springs BasicErrorController class.

You can instantiate the above ErrorController like this in a @Configuration file:

 @Autowired
 private ErrorAttributes errorAttributes;

 @Bean
 public AppErrorController appErrorController(){return new AppErrorController(errorAttributes);}

You can choose override the default ErrorAttributes by implementing ErrorAttributes. But in most cases the DefaultErrorAttributes should suffice.

axiopisty's user avatar

axiopisty

4,8708 gold badges43 silver badges72 bronze badges

answered Aug 5, 2015 at 16:50

owaism's user avatar

owaismowaism

1,0981 gold badge8 silver badges21 bronze badges

2

In my case the controller class was annotated with @Controller. Changing that to @RestController resolved the problem.
Basically @RestController is @Controller + @ResponseBody
So either use @RestController , or @Controller with @ResponseBody annotation with each method.

Some useful notes here : https://www.genuitec.com/spring-frameworkrestcontroller-vs-controller/

Markus's user avatar

Markus

2,0614 gold badges22 silver badges44 bronze badges

answered Sep 13, 2017 at 5:43

mykey's user avatar

mykeymykey

1,64318 silver badges13 bronze badges

3

in my case it because of package position , meaning package of controller must be above main class package

if my main class package is package co.companyname.spring.tutorial; any controller package should package co.companyname.spring.tutorial.WHAT_EVER_HERE;

package co.companyname.spring.tutorial; // package for main class
@SpringBootApplication
public class FirstProjectApplication {

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


package co.companyname.spring.tutorial.controllers; // package for controllers 

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

@RestController 
public class HelloController { 

@RequestMapping("/hello")  
public String hello() {   
 return "Hello, world"; 
 }}

after finish coding press boot dashboard

enter image description here

one last thing to make sure your controller is mapping or not just console you should see somehting smilliar

Mapped "{[/hello]}" onto public java.lang.String co.companyname.spring.tutorial.controllers.HelloController.hello()

happy coding

answered Sep 28, 2016 at 12:31

Mina Fawzy's user avatar

Mina FawzyMina Fawzy

20.6k16 gold badges130 silver badges149 bronze badges

Try adding the dependency.

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

answered Dec 6, 2016 at 12:22

Sree's user avatar

SreeSree

1531 silver badge2 bronze badges

4

This happens when an explicit error page is not defined. To define an error page, create a mapping of /error with a view.
e.g. the below code maps to a string value being returned in case of an error.

package com.rumango.controller;

import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class IndexController implements ErrorController{
    private final static String PATH = "/error";
    @Override
    @RequestMapping(PATH)
    @ResponseBody
    public String getErrorPath() {
        // TODO Auto-generated method stub
        return "No Mapping Found";
    }

}

Mohit Kanwar's user avatar

Mohit Kanwar

2,8797 gold badges38 silver badges58 bronze badges

answered Nov 12, 2018 at 6:55

prabhat kumar's user avatar

2

By default spring boot will scan current package for bean definition. So if your current package where main class is defined and controller package is not same or controller package is not child package of your main app package it will not scan the controller. To solve this issue one can include list of packages for bean definition in main package

@SpringBootApplication(scanBasePackages = {"com.module.restapi1.controller"})

or create a hierarchy of package where child package is derived from main package

package com.module.restapi;
package com.module.restapi.controller

answered Apr 24, 2020 at 10:08

anand shukla's user avatar

1

In the main class, after the configuration «@SpringBootApplication», adding «@ComponentScan» without having any arguments, worked for me !!!

Main Class :

@SpringBootApplication
@ComponentScan
public class CommentStoreApplication {

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

    }
}

RestController Class :

@RestController
public class CommentStoreApp {

    @RequestMapping("/") 
    public String hello() {
        return "Hello World!";
    }
}

P.S: Don’t miss to run mvn clean and mvn install commands, before launching the application

answered Mar 1, 2018 at 11:28

Harika's user avatar

HarikaHarika

711 silver badge1 bronze badge

1

I am developing Spring Boot application for a few weeks.. And I was gettig same error like below;

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

When I get this error massage I realized my controller or rest controller class is not defined in my project. I mean our all controller packages aren’t same package with main class which include @SpringBootApplication annotation.. I mean you need to add you controller package’s name to @ComponentScan annotation to your main class which is includes @SpringBootApplication annotation. If you write codes of below your problem will be solving… Most important thing is you have to add your all controller’s package to @ComponentScan annotation like I did in the below

package com.example.demo;

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

@SpringBootApplication
@ComponentScan({ "com.controller.package1, com.controller.package2, com.controller.package3, com.controller.packageN", "controller", "service" } // If our Controller class or Service class is not in the same packages we have //to add packages's name like this...directory(package) with main class
public class MainApp {
    public static void main(String[] args) {
        SpringApplication.run(MainApp.class, args);
    }
}

I hope this codes are going to help someone…

If you find another way to solve this error or you have some suggestions for me,
please write to comments… thanks…

answered Jan 18, 2018 at 11:33

Semih Erkaraca's user avatar

I added this dependency and it solved my problem.

<dependency>
    <groupId>org.springframework.boot</groupId>

    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

Pang's user avatar

Pang

9,365146 gold badges85 silver badges121 bronze badges

answered Mar 19, 2017 at 14:21

Sylvester Oguikpu's user avatar

1

You might be getting the error i.e.

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

This is because it is not scanning your Controller & Service classes which you have to specify in your main() class like this,

package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@EnableAutoConfiguration
**@ComponentScan({"com.example.demo", "controller", "service"})**
public class SpringBootMvcExample1Application {
    public static void main(String[] args) {
        SpringApplication.run(SpringBootMvcExample1Application.class, args);
    }
}

Note: Here, I have specified various classes like demo, controller and service to be scanned then only it will work properly.

Soren's user avatar

Soren

14.3k4 gold badges40 silver badges67 bronze badges

answered May 21, 2017 at 18:11

Rupesh Bharuka's user avatar

Quite late to the party. As per spring official documentation «Spring Boot installs a whitelabel error page that you see in a browser client if you encounter a server error.»
https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#howto-customize-the-whitelabel-error-page

  1. You can disable the feature by setting server.error.whitelabel.enabled=false in application.yml or application.properties file.

2.Recommended way is set your error page so that end user can understand. Under resources/templates folder create a error.html file and add dependency in pom.xml file

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

Spring will automatically choose the error.html page as the default error template.
Note:- Don’t forget to update maven project after adding dependency.

answered Sep 8, 2019 at 12:12

Joginder Malik's user avatar

1

You have to organize the packages so that the package containing public static main(or where you wrote @SpringBootApplication), the father of all your other packages.

ppreetikaa's user avatar

ppreetikaa

1,1292 gold badges15 silver badges22 bronze badges

answered May 9, 2019 at 10:16

sakgeek's user avatar

1

The problem is that you are navigating to localhost:8080/ instead of localhost:8080/upload as prescribed in the guide. Spring Boot has a default error page used when you navigate to an undefined route to avoid giving away server specific details (which can be viewed as a security risk).

You’re options are to either: visit the right page, add your own landing page, or override the white error page.

To simplify this particular situation, I updated the guide so that it uses / instead of /upload.

answered Apr 25, 2016 at 15:46

gregturn's user avatar

gregturngregturn

2,6253 gold badges25 silver badges40 bronze badges

I too got the same error and was able to resolve the error by adding the below dependency to my pom.xml.

<dependency>
    <groupId>org.apache.tomcat.embed</groupId>
    <artifactId>tomcat-embed-jasper</artifactId>
    <scope>provided</scope>
</dependency>

Reason is we are using JSP as the view. Default embedded servlet container for Spring Boot Starter Web is tomcat.
To enable support for JSP’s, we would need to add a dependency on tomcat-embed-jasper.

In my case I was returning a JSP as view from controller.
Hope this answer helps someone who are struggling with same issue.

answered Nov 24, 2017 at 12:50

Sujana's user avatar

SujanaSujana

3311 gold badge3 silver badges12 bronze badges

I know it’s not exactly answer to question, but this question is first which appears on Google :)

Problem («This application has no explicit mapping for /error») appears when trying to access Swagger UI.

In my case problems were caused by @RestController(«/endpoint»), which isn’t handled properly by swagger.

So, this resulted in errors:

@RestController("/endpoint")
public class EndpointController {

And this was fine

@RestController
@RequestMapping("/endpoint")
public class EndpointController {

answered Apr 17, 2018 at 13:28

Elas's user avatar

ElasElas

2125 silver badges15 bronze badges

this can happen if you forget the @RestController annotation on top of your controller class
import import org.springframework.web.bind.annotation.RestController;

and add the annotation as below

refer the simple example below

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


@RestController
public class HelloController {
@RequestMapping("/")
    public String index() {
        return "Greetings from Spring Boot!";
    }

}

answered Feb 7, 2019 at 5:57

Sithija Piyuman Thewa Hettige's user avatar

I need to mention this way and give the reference to packages and it worked out. You may exclude @EnableAutoConfiguration this annotation but required for me to bypass any DB related depenencies.

@SpringBootApplication
@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
@ComponentScan(basePackages = {"your package 1", "your package2"})

public class CommentStoreApplication {

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

    }
}

answered Oct 31, 2019 at 11:31

Suresh's user avatar

SureshSuresh

1,3072 gold badges20 silver badges26 bronze badges

Same problem I have faced recently. I have solved it by just getter and setter method spelling correction!

answered Nov 18, 2021 at 23:47

Abdus Salam's user avatar

1

The tutorial expects you to have the Thymeleaf template engine in classpath. I ran into the same problem and finally figured this out. I’ll reach out to the tutorial author to include that info.

The easiest way if you’ve followed the tutorial is to add the dependency to your pom.xml in the project root folder. Next time you run your app Spring will detect Thymeleaf and use the uploadform template

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

For the full example see their Github repository.

answered Apr 22, 2016 at 15:25

toomasr's user avatar

toomasrtoomasr

4,6712 gold badges31 silver badges36 bronze badges

1

Change @Controller to @RestController in your controller class and everything should go smoothly.

answered Nov 16, 2017 at 16:08

supernova's user avatar

supernovasupernova

2,9614 gold badges32 silver badges30 bronze badges

I was facing the same problem, using gradle and it got solved on adding following dependencies-

compile('org.springframework.boot:spring-boot-starter-data-jpa')
compile('org.springframework.boot:spring-boot-starter-web')
testCompile('org.springframework.boot:spring-boot-starter-test')
compile('org.apache.tomcat.embed:tomcat-embed-jasper')

earlier I was missing the last one causing the same error.

answered Jul 18, 2018 at 12:34

siddhartha attri's user avatar

2

I was facing this issue and then later realized that I was missing the @Configuration annotation in the MvcConfig class which basically does the mapping for ViewControllers and setViewNames.

Here is the content of the file :

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
**@Configuration**
public class MvcConfig implements WebMvcConfigurer{
   public void addViewControllers(ViewControllerRegistry registry)
   {
      registry.addViewController("/").setViewName("login");
      registry.addViewController("/login").setViewName("login");
      registry.addViewController("/dashboard").setViewName("dashboard");
   }
}

Hope this helps somebody!!

Unheilig's user avatar

Unheilig

16.1k193 gold badges67 silver badges96 bronze badges

answered Oct 8, 2018 at 4:03

Arupesh RoyChowdhury's user avatar

1

Make sure @RestController annotation is added right after the @SpringBootApplication.
RestController annotation tells Spring that this code describes an endpoint that should be made available over the web.

answered Aug 1, 2020 at 18:43

Bimal Parajuli's user avatar

You may have not included thymleaf in your pom.xml file.

answered Apr 12, 2021 at 14:12

alphcoder's user avatar

I had a similar problem. And I had Main.class on the top of all the controllers, yet I was facing this issue. All I needed to do is to create a separate swagger configuration file and initialize docket bean in it.

note: location of this file should be either in the same package of the Main.class file or in a package inside that main package.

SwaggerCongiguration.java file

package com.example.springDataJPAUsingGradle;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket docket() {
        return new Docket(DocumentationType.SWAGGER_2).select().build();
    }
}

I also had to add @RequestMapping("/api") in my controller.java.
Here’s how:

package com.example.springDataJPAUsingGradle.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.springDataJPAUsingGradle.service.StudentService;

@RestController
@RequestMapping("/api")
public class StudentController {

    @Autowired(required = true)
    @GetMapping("/home")
    public String home() {
        return "Welcome to home page";
    }
}

Then after hitting the url: http://localhost:9090/your-app-root/swagger-ui/ swagger UI will be visible.
For eg, in my case the url is: http://localhost:9090/students/swagger-ui/

answered Jul 7, 2021 at 7:58

Himanjli Jain's user avatar

0

All I have done to solve this kind of problem is to mention anotation @Configuration in MVCConfig Class.

Like this one :

package com.example;

/**
 * Created by sartika.s.hasibuan on 1/10/2017.
 */
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@EnableAutoConfiguration
@Configuration
@ComponentScan
public class MvcConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/home").setViewName("home");
        registry.addViewController("/").setViewName("home");
        registry.addViewController("/hello").setViewName("hello");
        registry.addViewController("/login").setViewName("login");
    }

}

Ole V.V.'s user avatar

Ole V.V.

79.7k15 gold badges133 silver badges153 bronze badges

answered Jan 10, 2017 at 4:19

Sartika Hasibuan's user avatar

I had a similar mistake, I use the spring boot and velocity, my solution is to check the file application.properties, spring.velocity.toolbox-config-location found that this property is wrong

answered Apr 24, 2017 at 14:22

叶为正's user avatar

叶为正叶为正

811 silver badge2 bronze badges

0

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.

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

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

In our project we are using 3.0.0-SNAPSHOT of swagger springfox.

Recently when we open swagger-ui.html, it is giving 404 Whilte Label Error.

I enabled logs at web level

`

logging.level.web=TRACE
logging.level.org.springframework.web=TRACE

`

It is loading «/swagger-resources», but not loading «/swagger-ui.html»

The addition of the resource handler is as per the document.

When loading «/swagger-ui.html», it’s giving «Resource not found»

`

web.server.adapter.HttpWebHandlerAdapter.traceDebug - [74c4396b] HTTP GET "/swagger-resources/", headers={masked}
web.reactive.result.method.annotation.RequestMappingHandlerMapping.lambda$getHandler$1 - [74c4396b] Mapped to public org.springframework.http.ResponseEntity<java.util.List<springfox.documentation.swagger.web.SwaggerResource>> springfox.documentation.swagger.web.ApiResourceController.swaggerResources()
web.reactive.result.method.annotation.ResponseEntityResultHandler.selectMediaType - Using 'application/json;q=0.8' given [text/html, application/xhtml+xml, image/webp, image/apng, application/xml;q=0.9, application/signed-exchange;v=b3;q=0.9, */*;q=0.8] and supported [application/json]
web.reactive.result.method.annotation.ResponseEntityResultHandler.writeBody - [74c4396b] 0..1 [java.util.List<springfox.documentation.swagger.web.SwaggerResource>]
http.codec.json.Jackson2JsonEncoder.trace - [74c4396b] Encoding [[springfox.documentation.swagger.web.SwaggerResource@4903f26e, springfox.documentation.swagger.web.SwaggerResource@57b46085, springfox.documentation.swagger.web.SwaggerResource@4beb0f82, springfox.documentation.swagger.web.SwaggerResource@3a6db652, springfox.documentation.swagger.web.SwaggerResource@6caba3f3, springfox.documentation.swagger.web.SwaggerResource@18ef56ab, springfox.documentation.swagger.web.SwaggerResource@b6bcd2b, springfox.documentation.swagger.web.SwaggerResource@5ce32532, springfox.documentation.swagger.web.SwaggerResource@6d66b166, springfox.documentation.swagger.web.SwaggerResource@fdef86f, springfox.documentation.swagger.web.SwaggerResource@5a096e2a, springfox.documentation.swagger.web.SwaggerResource@1f060aec, springfox.documentation.swagger.web.SwaggerResource@473365eb, springfox.documentation.swagger.web.SwaggerResource@3fd6e0e2]]
web.server.adapter.HttpWebHandlerAdapter.traceDebug - [74c4396b] Completed 200 OK, headers={masked}
http.server.reactive.ReactorHttpHandlerAdapter.trace - [74c4396b] Handling completed

web.server.adapter.HttpWebHandlerAdapter.traceDebug - [74c4396b] HTTP GET "/swagger-ui.html", headers={masked}
web.reactive.handler.SimpleUrlHandlerMapping.lookupHandler - [74c4396b] Matching patterns [/swagger-ui.html**, /**]
web.reactive.handler.SimpleUrlHandlerMapping.lambda$getHandler$1 - [74c4396b] Mapped to ResourceWebHandler ["classpath:/META-INF/resources/"]
web.reactive.resource.ResourceWebHandler.lambda$handle$0 - [74c4396b] Resource not found
web.reactive.function.server.RouterFunctions.route - [74c4396b] Matched org.springframework.boot.autoconfigure.web.reactive.error.DefaultErrorWebExceptionHandler$$Lambda$1372/0x00000008008bb040@10209892
web.HttpLogging.debug - [74c4396b] Resolved [ResponseStatusException: 404 NOT_FOUND] for HTTP GET /swagger-ui.html
core.codec.CharSequenceEncoder.trace - [74c4396b] Writing "<html><body><h1>Whitelabel Error Page</h1><p>This application has no configured error view, so you are seeing this as a fallback.</p><div id='created'>Thu Jul 02 22:15:45 IST 2020</div><div>There was an unexpected error (type=Not Found, status=404).</div></body></html>"
web.server.adapter.HttpWebHandlerAdapter.traceDebug - [74c4396b] Completed 404 NOT_FOUND, headers={masked}
http.server.reactive.ReactorHttpHandlerAdapter.trace - [74c4396b] Handling completed

`

I checked if path inside META-INF is changed or not as per documentation at https://springfox.github.io/springfox/docs/snapshot/#snapshot-3, it is same as V 2.10.5

Then, when I changed version from V 3 Snapshot to current stable 2.10.5, it worked.

Can you let me know what I am missing? And since I am a noobie, can you tell me is snapshot version is like beta version which should not be used in production?

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

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:

Details
Written by  
Last Updated on 24 March 2022   |   Print  Email

In this article, I will help you understand the default error handling in Spring Boot, how to use custom error pages (for common HTTP error codes like 403, 404, 500…) and how to code a custom error controller in order to perform additional code when an error occurred, e.g. logging more information about the error.

 

1. Default Whitelabel Error Page

By default, Spring Boot will display the Whitelabel error page when an error occurred. For example, when a page could not be found (HTTP 404 error):

spring boot whitelable error 404

Or when an exception is thrown by Java Virtual Machine, causing HTTP 500 Internal server error – the white label error page gets displayed with the exception stack trace:

spring boot whitelable error 500

This kind of error page is certainly not friendly to the end users, and Spring Boot prints this statement:

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

That means programmers should handle mapping for /error URL and provide custom, user-friendly error pages.

Spring Boot allows programmers to disable the white label error page by setting the following property in the application.properties file:

server.error.whitelabel.enabled=false

Then the raw error page provided by the server gets displayed, i.e. Tomcat like this:

tomcat internal server error

Anyway, we should provide custom error pages instead of the default ones which are very technical to the end users.

 

2. Use Custom Error Pages

Spring Boot makes it easy to override the default whitelabel error page. Just create the error.html page under the src/main/resources/templates directory. For example, with the following code:

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Error</title>
</head>
<body>
	<h3>Sorry, there was an error occurred!</h3>
</body>
</html>

Then when any error occurred, this custom error page will get displayed:

general custom error page

You can also provide custom error page for a specific HTTP status code (403, 404, 500, etc) – just by creating the 403.html (Forbidden error), 404.html (Page not found error), 500.html (Internal server error)… files under the templates/error directory (you must create error directory):

custome error pages in spring boot project

That’s it – very simple! Thanks to Spring Boot’s default configurations do all the details behind the scene.

 

3. Implement Custom Error Controller

In case you want to perform some tasks before the custom error pages get displayed, you can code a controller class implementing the ErrorController interface like this:

package net.codejava;

import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;

import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class CustomErrorController  implements ErrorController {

	@GetMapping("/error")
	public String handleError(HttpServletRequest request) {
		String errorPage = "error";	// default
		
		Object status = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
		
		if (status != null) {
			Integer statusCode = Integer.valueOf(status.toString());
			
			if (statusCode == HttpStatus.NOT_FOUND.value()) {
				// handle HTTP 404 Not Found error
				errorPage = "error/404";
				
			} else if (statusCode == HttpStatus.FORBIDDEN.value()) {
				// handle HTTP 403 Forbidden error
				errorPage = "error/403";
				
			} else if (statusCode == HttpStatus.INTERNAL_SERVER_ERROR.value()) {
				// handle HTTP 500 Internal Server error
				errorPage = "error/500";
				
			}
		}
		
		return errorPage;
	}
	
	@Override
	public String getErrorPath() {
		return "/error";
	}
}

Here, the getErrorPath() method returns a URL to which will be forwarded when an error occurs. And this error path is handled by the handler method right in this class. I showed you the code that returns the corresponding error page name based on HTTP status code, and you can add code to perform the logics you want to execute before the error pages get displayed.

Note that all exceptions are logged by Spring Boot by default, so you don’t have to log the errors again here in this custom controller class.

In case you want to handle specific exception classes rather than HTTP error code, follow this article: Spring Boot Controller-Based Exception Handler Examples

 

Conclusion

So far you have learned how to provide custom error pages in a Spring Boot application, and how to intercept the requests before those error pages get displayed. Again, Spring Boot makes error handling simple, easy and convenient. For reference, you can download the sample Spring Boot project attached below, and watch the following video to see the code in action:

 

Related Tutorials:

  • Spring Boot Controller-Based Exception Handler Examples
  • How to handle exceptions in Spring MVC

 

Other Spring Boot Tutorials:

  • Spring Boot automatic restart using Spring Boot DevTools
  • Spring Boot Form Handling Tutorial with Spring Form Tags and JSP
  • How to create a Spring Boot Web Application (Spring MVC with JSP/ThymeLeaf)
  • Spring Boot — Spring Data JPA — MySQL Example
  • Spring Boot Hello World RESTful Web Services Tutorial
  • How to use JDBC with Spring Boot
  • Spring Boot CRUD Web Application with JDBC — Thymeleaf — Oracle
  • Spring Boot RESTful CRUD API Examples with MySQL database
  • How to package Spring Boot application to JAR and WAR
  • Spring Boot Security Authentication with JPA, Hibernate and MySQL
  • Spring Data JPA Paging and Sorting Examples

 

About the Author:

Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.

Add comment

Понравилась статья? Поделить с друзьями:
  • This application has encountered a critical error wow как исправить
  • This application has encountered a critical error wow error 132
  • This application has encountered a critical error warcraft 3 frozen throne
  • This application has encountered a critical error war3
  • This application has encountered a critical error uwow