This application has no explicit mapping for error

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

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

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:

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

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

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

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

Понравилась статья? Поделить с друзьями:
  • This application has no configured error view so you are seeing this as a fallback
  • This application has encountered a critical error перевод
  • This application has encountered a critical error недостаточно памяти для обработки команды
  • This application has encountered a critical error wow как исправить
  • This application has encountered a critical error wow error 132