1. 程式人生 > >Spring Boot 探索之旅(五)——Web支援

Spring Boot 探索之旅(五)——Web支援

一、Spring MVC配置

/**
 * 主要WebMvc配置
 * @author sunyiran
 * @date 2018-09-29
 */
@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {

    /**
     * 註冊自定義攔截器
     * @param registry
     */
    @Override
    protected void addInterceptors(InterceptorRegistry registry) {
        super.addInterceptors(registry);
    }

    /**
     * 註冊檢視對映
     * @param registry
     */
    @Override
    protected void addViewControllers(ViewControllerRegistry registry) {
        super.addViewControllers(registry);
    }

    /**
     * 註冊資源對映
     * @param registry
     */
    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        super.addResourceHandlers(registry);
    }

    /**
     *
     * @param registry
     */
    @Override
    protected void addFormatters(FormatterRegistry registry) {
        super.addFormatters(registry);
    }

    /**
     * 配置轉化器
     * @param converters
     */
    @Override
    protected void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        super.configureMessageConverters(converters);
    }

    /**
     * 配置異常處理器
     * @param exceptionResolvers
     */
    @Override
    protected void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> exceptionResolvers) {
        super.configureHandlerExceptionResolvers(exceptionResolvers);
    }

    /**
     * 配置跨域請求
     * @param registry
     */
    @Override
    protected void addCorsMappings(CorsRegistry registry) {
        super.addCorsMappings(registry);
    }
}

1.1 配置檢視對映

目標:瀏覽器中輸入localhost:8082,能定位到非預設首頁index.html,而是訪問first.html

第一步、編寫檢視對映程式碼,viewController為訪問相對路徑,viewName為檢視名

 /**
     * 註冊檢視對映
     * @param registry
     */
    @Override
    protected void addViewControllers(ViewControllerRegistry registry) {
        /*訪問相對路徑為/時,對映至first,結合模版前後綴,跳轉值/templates/first.html*/
        registry.addViewController("/").setViewName("first");
        super.addViewControllers(registry);
    }

第二步、啟動專案,測試