阅读110 返回首页    go 阿里云 go 技术社区[云栖]


《精通Spring MVC 4》——1.7 错误与转码配置

本节书摘来自异步社区《精通Spring MVC 4》一书中的第1章,第1.7节,作者:【美】Geoffroy Warin着,更多章节内容可以访问云栖社区“异步社区”公众号查看

1.7 错误与转码配置

还记得在没有添加控制器的时候,第一次启动应用吗?当时看到了一个有意思的“Whitelabel Error Page”输出。

错误处理要比看上去更麻烦一些,尤其是在没有web.xml配置文件并且希望应用能够跨Web服务器部署时更是如此。好消息是Spring Boot将会处理这些事情!让我们看一下ErrorMvcAutoConfiguration:

ConditionalOnClass({ Servlet.class, DispatcherServlet.class })
@ConditionalOnWebApplication
// Ensure this loads before the main WebMvcAutoConfiguration so that
the error View is
// available
@AutoConfigureBefore(WebMvcAutoConfiguration.class)
@Configuration
public class ErrorMvcAutoConfiguration implements
EmbeddedServletContainerCustomizer,
        Ordered {

    @Value("${error.path:/error}")
    private String errorPath = "/error";

    @Autowired
    private ServerProperties properties;

    @Override
    public int getOrder() {
        return 0;
    }

    @Bean
    @ConditionalOnMissingBean(value = ErrorAttributes.class, search =
SearchStrategy.CURRENT)
    public DefaultErrorAttributes errorAttributes() {
        return new DefaultErrorAttributes();
    }

    @Bean
    @ConditionalOnMissingBean(value = ErrorController.class, search =
SearchStrategy.CURRENT)
    public BasicErrorController basicErrorController(ErrorAttributes
errorAttributes) {
        return new BasicErrorController(errorAttributes);
    }
    @Override
    public void customize(ConfigurableEmbeddedServletContainer
container) {
        container.addErrorPages(new ErrorPage(this.properties.
getServletPrefix()
                + this.errorPath));
    }

    @Configuration
    @ConditionalOnProperty(prefix = "error.whitelabel", name =
"enabled", matchIfMissing = true)
    @Conditional(ErrorTemplateMissingCondition.class)
    protected static class WhitelabelErrorViewConfiguration {

        private final SpelView defaultErrorView = new SpelView(
                "<html><body><h1>Whitelabel Error Page</h1>"
                        + "<p>This application has no explicit mapping
for /error, so you are seeing this as a fallback.</p>"
                        + "<div id='created'>${timestamp}</div>"
                        + "<div>There was an unexpected error
(type=${error}, status=${status}).</div>"
                        + "<div>${message}</div></body></html>");

        @Bean(name = "error")
        @ConditionalOnMissingBean(name = "error")
        public View defaultErrorView() {
            return this.defaultErrorView;
        }

        // If the user adds @EnableWebMvc then the bean name view
resolver from
        // WebMvcAutoConfiguration disappears, so add it back in to
avoid disappointment.
        @Bean
        @ConditionalOnMissingBean(BeanNameViewResolver.class)
        public BeanNameViewResolver beanNameViewResolver() {
            BeanNameViewResolver resolver = new
BeanNameViewResolver();
            resolver.setOrder(Ordered.LOWEST_PRECEDENCE - 10);
            return resolver;
        }
    }
}

这段配置都做了些什么呢?

定义了一个bean,即DefaultErrorAttributes,它通过特定的属性暴露了有用的错误信息,这些属性包括状态、错误码和相关的栈跟踪信息。
定义了一个BasicErrorController bean,这是一个MVC控制器,负责展现我们所看到的错误页面。
允许我们将Spring Boot的whitelabel错误页面设置为无效,这需要将配置文件application.properties中的error.whitelable.enabled设置为false。
我们还可以借助模板引擎提供自己的错误页面。例如,它的名字是error.html,ErrorTemplateMissingCondition条件会对此进行检查。
在本书后面的内容中,我们将会看到如何恰当地处理错误。

至于转码的问题,非常简单的HttpEncodingAutoConfiguration将会负责处理相关的事宜,这是通过提供Spring的CharacterEncodingFilter类来实现的。通过spring.http.encoding.charset配置,我们可以覆盖默认的编码(“UTF-8”),也可以通过spring.http.encoding.enabled禁用这项配置。

最后更新:2017-05-27 15:01:43

  上一篇:go  《精通Spring MVC 4》——1.8 嵌入式Servlet容器(Tomcat)的配置
  下一篇:go  《精通Spring MVC 4》——1.6 幕后的Spring Boot