相信大家從使用SSM框架到使用Springboot框架的過程中都會遇到這樣一個問題,SSM框架中的spring-mvc.xml配置文件在Springboot中被簡化了,那麼我一些原先需要使用配置文件配置的功能現在要怎麼辦呢?今天我就帶大家解決這個問題。
今天從配置URL路徑直接返回請求頁面及配置Interceptor攔截器兩個方面來進行介紹:
實現請求路徑直接跳轉到對應頁面的需求:
①創建Config類MyMvcConfig,並實現WebMvcConfigurer類
②實現addViewController方法,如下圖
public void addViewControllers(ViewControllerRegistry registry) {
//如下方法實現客戶端輸入"/showLogin"請求,則服務器直接返回templates.login.html頁面
registry.addViewController("/showLogin").setViewName("login");
}
③示例中方法即可實現客戶端輸入”/showLogin”請求,服務器就返回”templates.login.html”頁面
實現攔截器Interceptor配置:
①創建攔截器實現HandlerInterceptro類,實現preHandle、postHandle、afterCompletion方法。
②在自己創建的MyMvcConfig中添加addInterceptors方法,如下圖所示
public void addInterceptors(InterceptorRegistry registry) {
//如下方法實現使用MyInterceptor攔截客戶端發出的所有請求,除了"/test1"請求
registry.addInterceptor(new MyInterceptor()).addPathPatterns("/**").excludePathPatterns("/test1");
}
③ 示例方法的使用可以實現攔截所有請求,除了”/test1”請求
本人小白,如有問題歡迎回復討論
閱讀更多 鬼魅的程序湧上心頭 的文章