使用JSP解析器时,未启动Spring Boot 1.4中的自定义错误页面

时间:2016-12-07 10:49:15

标签: java jsp spring-boot error-handling

我试图在Spring Boot 1.4应用程序中使用自己的自定义错误页面。根据文档,将错误页面放在src/main/resources/public/error目录中就足够了(例如404.html)。

但是,我也在我的应用程序中使用JSP页面并为它们设置一个解析器:

@Override
public void configureViewResolvers(final ViewResolverRegistry registry) {
    final UrlBasedViewResolverRegistration resolver = registry.jsp("/WEB-INF/jsp/", ".jsp");

    final Map<String, Object> attributes = new HashMap<>();
    attributes.put("HASH", hashReader.getHashValue());
    attributes.put("Hoker", hookerReader.getHooker());
    resolver.attributes(attributes);
}

每当遇到4xx错误时,我会尝试加载resources/public/error而不是使用我放在/WEB-INF/jsp/error.jsp目录中的自定义错误页面。

有没有办法强制Spring Boot使用其默认行为而不是尝试将错误页面解析到JSP目录?

1 个答案:

答案 0 :(得分:1)

这是一个例子,https://github.com/lenicliu/eg-spring/tree/master/eg-spring-boot/eg-spring-boot-webmvc

我想你可以这样修理它:

package com.lenicliu.spring.boot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;
import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
import org.springframework.boot.web.servlet.ErrorPage;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpStatus;

@SpringBootApplication
public class Application {

    @Bean
    public EmbeddedServletContainerCustomizer customizeContainerr() {
        return new CustomizedContainer();
    }

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

    private static class CustomizedContainer implements EmbeddedServletContainerCustomizer {
        @Override
        public void customize(ConfigurableEmbeddedServletContainer container) {
            container.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/404.html"));
            container.addErrorPages(new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/500.html"));
        }
    }
}

你可以把404.html和500.html放到以下文件夹中:

src/main/resource/static/500.html
src/main/resource/static/404.html
像这样

container.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/error/404.html"));
container.addErrorPages(new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/error/500.html"));

然后将它们放入

src/main/resource/static/error/500.html
src/main/resource/static/error/404.html

参考http://docs.spring.io/spring-boot/docs/1.4.2.RELEASE/reference/htmlsingle/#boot-features-spring-mvc-static-content

/ static或/ public或/ resources或/ META-INF / resources,它们是相同的。

希望能帮助你:)