H2 console whitelabel error page

Java Questions

After trying to test connection to h2 database or connect whitelabel error occurs

After running Spring boot project and going to localhost:8080/h2-console and after trying to connect to my database I get whitelabel error when i click any button on h2-console screen. I am using in memory database. I am trying to connect to database with classic username:sa and password:(blank)
h2-console screen
Even after clicking Save i get whitelabel error
application properties:

spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.h2.console.enabled=true

pom xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.4</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.m2-2.0</groupId>
    <artifactId>test</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>test</name>
    <description>test project for mc2</description>
    <properties>
        <java.version>11</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <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>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
            <scope>runtime</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

configure method WebSecurityConfig class:

@Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/", "/home", "/h2-console/**").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
                .logout()
                .permitAll();
        http.headers().frameOptions().sameOrigin();
    }

Advertisement

Answer

After research i found out that spring security csrf blocks h2-console so what is needed to continue is to add next code to the WebSecurityConfig class

http
     .headers().frameOptions().sameOrigin();
http
     .csrf().disable();
http
     .headers().frameOptions().disable();

8 People found this is helpful

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.

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

pom.xml

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

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

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

</project>

Controller

package com.example.demo.controller;

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

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

DemoApplication

package com.example.demo;

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

@SpringBootApplication
public class DemoApplication {

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

}

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


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

How to resolve Whitelabel Error Page in Spring Boot

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

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

1. Custom Error Controller

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

ErrorrHandlerController.java

package org.websparrow.controller;

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

@RestController
public class ErrorrHandlerController implements ErrorController {

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

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

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

How to resolve Whitelabel Error Page in Spring Boot

2. Displaying Custom Error Page

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

error.html

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

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

</body>
</html>

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

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

3. Disabling the Whitelabel Error Page

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

application.properties

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

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

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

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

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

Main.java

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

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

}

References

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

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

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

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

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

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

image

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

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

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

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

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

image

image

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

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

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

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

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

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

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

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

image

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

image

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

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

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

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

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

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

public class CustomHandlerInterceptor implements HandlerInterceptor {

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

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

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

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

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

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

image

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

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

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

2.2, добавьте ErrorPage

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

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

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

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

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

image

image

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

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

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

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

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

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

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

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

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

image

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

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

image

image

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

image

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

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

     

    image

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

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

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

    private static final String ERROR_PATH = "/error";

    @Resource
    private SimpleUrlHandlerMapping simpleUrlHandlerMapping;

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

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

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

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

image

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

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

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

    private static final String ERROR_PATH = "/error";

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

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

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

Понравилась статья? Поделить с друзьями:
  • H13 ошибка пжд
  • H1222 ошибка бобкет
  • Half life 2 episode one runtime error
  • Hal uart overrun error
  • H114 ошибка кпд