閱讀110 返回首頁    go 小米 go 小米6


《精通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