Springboot實(shí)現(xiàn)WebMvcConfigurer接口定制mvc配置詳解
引言
spring boot拋棄了傳統(tǒng)xml配置文件,通過配置類(標(biāo)注@Configuration的類,@Configuration配置類相當(dāng)于一個(gè)xml配置文件)以JavaBean形式進(jìn)行相關(guān)配置。
正常情況下,spring boot的自動配置可以滿足我們的大部分需求。但在保留spring boot提供的便利,又需要增加額外SpringMVC配置的時(shí)候,可以自定義一個(gè)配置類(標(biāo)注@Configuration的類)并實(shí)現(xiàn)WebMvcConfigurer接口來定制SpringMvc配置
SpringBoot 1.5通過繼承WebMvcConfigurerAdapter抽象類來定制SpringMvc配置。SpringBoot 2.0后,WebMvcConfigurerAdapter抽象類過時(shí)了,改為實(shí)現(xiàn)WebMvcConfigurer接口來定制SpringMvc配置
/** * SpringBoot 1.5 */ @Configuration public class SpringMvcConfiguration extends WebMvcConfigurerAdapter { } ------------------------------------------------------------------------------------------- /** * SpringBoot 2.0 */ @Configuration public class SpringMvcConfiguration implements WebMvcConfigurer { }
WebMvcConfigurer接口源碼,具體可看WebMvcConfigurer官方文檔
package org.springframework.web.servlet.config.annotation; import java.util.List; import org.springframework.core.convert.converter.Converter; import org.springframework.format.Formatter; import org.springframework.format.FormatterRegistry; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.lang.Nullable; import org.springframework.validation.MessageCodesResolver; import org.springframework.validation.Validator; import org.springframework.web.method.support.HandlerMethodArgumentResolver; import org.springframework.web.method.support.HandlerMethodReturnValueHandler; import org.springframework.web.servlet.DispatcherServlet; import org.springframework.web.servlet.HandlerExceptionResolver; import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter; /** * 采用JavaBean的形式代替?zhèn)鹘y(tǒng)的xml配置文件對Spring MVC進(jìn)行定制 */ public interface WebMvcConfigurer { //幫助配置HandlerMappings路徑匹配選項(xiàng),例如尾部斜杠匹配,后綴注冊,路徑匹配器和路徑幫助器 default void configurePathMatch(PathMatchConfigurer configurer) { } //配置內(nèi)容協(xié)商選項(xiàng) default void configureContentNegotiation(ContentNegotiationConfigurer configurer) { } //配置異步請求處理選項(xiàng) default void configureAsyncSupport(AsyncSupportConfigurer configurer) { } //通過轉(zhuǎn)發(fā)到Servlet容器的“默認(rèn)” Servlet,配置處理程序以委派未處理的請求 default void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { } //除了默認(rèn)注冊的之外,還添加Converters和Formatters default void addFormatters(FormatterRegistry registry) { } //添加Spring MVC生命周期攔截器,以對控制器方法調(diào)用和資源處理程序請求進(jìn)行預(yù)處理 default void addInterceptors(InterceptorRegistry registry) { } //添加處理程序以從Web應(yīng)用程序根目錄,類路徑等中的特定位置提供靜態(tài)資源,例如圖像,js和css文件 default void addResourceHandlers(ResourceHandlerRegistry registry) { } //配置跨源請求處理 default void addCorsMappings(CorsRegistry registry) { } //配置預(yù)先配置了響應(yīng)狀態(tài)代碼和/或用于呈現(xiàn)響應(yīng)主體的視圖的簡單自動化控制器 default void addViewControllers(ViewControllerRegistry registry) { } //配置視圖解析器,以將從控制器返回的基于字符串的視圖名稱轉(zhuǎn)換為具體的View 實(shí)現(xiàn)以執(zhí)行渲染 default void configureViewResolvers(ViewResolverRegistry registry) { } //添加解析器以支持自定義控制器方法參數(shù)類型 default void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) { } //添加處理程序以支持自定義控制器方法返回值類型 default void addReturnValueHandlers(List<HandlerMethodReturnValueHandler> handlers) { } //配置HttpMessageConverters用于讀取或?qū)懭胝埱蠡蝽憫?yīng)主體的 default void configureMessageConverters(List<HttpMessageConverter<?>> converters) { } //提供MessageCodesResolver用于從數(shù)據(jù)綁定和驗(yàn)證錯(cuò)誤代碼構(gòu)建消息代碼的自定義 default void extendMessageConverters(List<HttpMessageConverter<?>> converters) { } //配置異常解析器 default void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> resolvers) { } //擴(kuò)展或修改默認(rèn)配置的異常解析器列表 default void extendHandlerExceptionResolvers(List<HandlerExceptionResolver> resolvers) { } //提供MessageCodesResolver用于從數(shù)據(jù)綁定和驗(yàn)證錯(cuò)誤代碼構(gòu)建消息代碼的自定義 default MessageCodesResolver getMessageCodesResolver() { return null; } }
WebMvcConfigurer接口中定義了許多SpringMvc相關(guān)的方法,通過在配置類中重寫相應(yīng)的方法即可定制相關(guān)的SpringMvc配置,下面我會挑幾個(gè)較常用的方法進(jìn)行解析
自定義靜態(tài)資源映射 addResourceHandlers()
spring boot默認(rèn)將 /** 靜態(tài)資源訪問映射到 classpath:/static/ 目錄下.
如果spring boot的默認(rèn)配置不能滿足你的需求或你想修改它的默認(rèn)配置,則可定義一個(gè)配置類來實(shí)現(xiàn)WebMvcConfigurer接口,并重寫它的addResourceHandlers()方法來定制靜態(tài)資源訪問映射訪問映射。
import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.*; @Configuration public class SpringMvcConfiguration implements WebMvcConfigurer { /** * 添加靜態(tài)資源訪問映射配置 * @param registry */ @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/js/**").addResourceLocations("classpath:/static/js/"); registry.addResourceHandler("/css/**").addResourceLocations("classpath:/static/css/"); registry.addResourceHandler("/image/**").addResourceLocations("classpath:/static/image/"); //意思是:url中讀取到/upload時(shí),就會自動將/upload解析成D:/idea/java_workspace/image/upload registry.addResourceHandler("/upload/**").addResourceLocations("file:D:/idea/java_workspace/image/upload/"); /** * Linux系統(tǒng) * registry.addResourceHandler("/upload/**").addResourceLocations("file:/home/image/upload/"); */ } }
- addResourceHandler(“xxx”) 用于指定對外暴露的訪問路徑;
- addResourceLocations(“xxx”) 用于指定文件放置的目錄;
文件的放置目錄分兩種:項(xiàng)目內(nèi)部的文件 和 項(xiàng)目外部的文件;具體配置方式如下:
//配置內(nèi)部靜態(tài)資源文件訪問映射 registry.addResourceHandler("/image/**").addResourceLocations("classpath:/static/image/"); //配置外部靜態(tài)資源文件訪問映射(Windows系統(tǒng)) registry.addResourceHandler("/image/**").addResourceLocations("file:D:/idea/java_workspace/image/"); //配置外部靜態(tài)資源文件訪問映射(Linux系統(tǒng)) registry.addResourceHandler("/image/**").addResourceLocations("file:/home/image/");
友情提示:內(nèi)部靜態(tài)資源文件一般使用spring boot的默認(rèn)配置即可(即:將 /** 靜態(tài)資源訪問映射到 classpath:/static/ 目錄);重寫addResourceHandlers()方法一般用來定制外部靜態(tài)資源的訪問映射。
攔截器 addInterceptors()
import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.*; @Configuration public class SpringMvcConfiguration implements WebMvcConfigurer { /** * 添加攔截器鏈配置 * @param registry */ @Override public void addInterceptors(InterceptorRegistry registry) { //注冊攔截器1,對商家管理系統(tǒng)進(jìn)行權(quán)限驗(yàn)證 InterceptorRegistration registration1 = registry.addInterceptor(new ShopAdminInterceptor()); //指定攔截器1要攔截的請求(支持*通配符) registration1.addPathPatterns("/shop_admin/**"); //注冊攔截器2,對超級管理員系統(tǒng)進(jìn)行權(quán)限驗(yàn)證 InterceptorRegistration registration2 = registry.addInterceptor(new SuperAdminInterceptor()); /*指定攔截器2要攔截的請求(支持*通配符)*/ registration2.addPathPatterns("/super_admin/**"); //指定攔截器2不攔截的請求(支持*通配符) registration2.excludePathPatterns("/super_admin/toLogin"); } }
自定義攔截器類1
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class ShopAdminInterceptor extends HandlerInterceptorAdapter { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { //獲取用戶登陸信息 Person person = (Person) request.getSession().getAttribute("person"); //判斷用戶是否有權(quán)限進(jìn)入商家管理后臺系統(tǒng) if(person != null && person.getUserId() > 0 && person.getEnableStatus() == 1 && person.getPersonType() == 2){ //如果驗(yàn)證通過,則返回true,放行請求,即用戶接下來的操作可以正常執(zhí)行 return true; } //如果不滿足登陸驗(yàn)證,則跳轉(zhuǎn)到登陸頁面 response.sendRedirect("/o2o/local/to_login"); return false; } }
自定義攔截器類2
import com.cd.o2o2.entity.Person; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class SuperAdminInterceptor extends HandlerInterceptorAdapter { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { //獲取用戶登陸信息 Person person = (Person) request.getSession().getAttribute("person"); //判斷用戶是否有權(quán)限進(jìn)入超級管理員后臺系統(tǒng) if(person != null && person.getUserId() > 0 && person.getEnableStatus() == 1 && person.getPersonType() == 3){ //如果驗(yàn)證通過,則返回true,放行請求,即用戶接下來的操作可以正常執(zhí)行 return true; } //如果不滿足登陸驗(yàn)證,則跳轉(zhuǎn)到登陸頁面 response.sendRedirect("/o2o/local/to_login"); return false; } }
無業(yè)務(wù)邏輯頁面跳轉(zhuǎn) addViewControllers()
項(xiàng)目開發(fā)中,時(shí)常會涉及到無業(yè)務(wù)邏輯的頁面跳轉(zhuǎn); 這個(gè)頁面跳轉(zhuǎn)沒有涉及到任何的業(yè)務(wù)邏輯,只是單純的路由跳轉(zhuǎn)過程;但卻需要在Controller中編寫路由方法來完成,每一個(gè)頁面跳轉(zhuǎn)都需要定義一個(gè)路由方法,個(gè)人感覺是挺麻煩滴。
import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller @RequestMapping("/frontend") public class FrontendController { /** * 首頁路由 */ @RequestMapping("/index") private String index(){ return "frontend/index"; } /** * 店鋪列表路由 */ @RequestMapping("/to_shop_list") private String toShopList(){ return "frontend/shop_list"; } /** * 店鋪列表路由 */ @RequestMapping("/shop_detail") private String shopDetail(){ return "frontend/shop_detail"; } }
SpringBoot中,可以通過重寫addViewControllers()方法來配置無業(yè)務(wù)邏輯的頁面跳轉(zhuǎn); 擺脫路由方法這個(gè)麻煩,當(dāng)然你習(xí)慣使用路由方法來實(shí)現(xiàn)無業(yè)務(wù)邏輯的頁面跳轉(zhuǎn)也是沒問題滴哦.
import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.*; @Configuration public class SpringMvcConfiguration implements WebMvcConfigurer { /** * 添加無業(yè)務(wù)邏輯頁面跳轉(zhuǎn)配置 * @param registry */ @Override public void addViewControllers(ViewControllerRegistry registry) { //首頁路由 registry.addViewController("/frontend/index").setViewName("frontend/index"); //店鋪列表路由 registry.addViewController("/frontend/to_shop_list").setViewName("frontend/shop_list"); //店鋪列表路由 registry.addViewController("/frontend/shop_detail").setViewName("frontend/shop_detail"); } }
合而為一
package com.cd.o2o2.config.web; import com.cd.o2o2.interceptor.ShopAdminInterceptor; import com.cd.o2o2.interceptor.SuperAdminInterceptor; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.*; @Configuration public class SpringMvcConfiguration implements WebMvcConfigurer { /** * 添加靜態(tài)資源訪問映射配置 */ @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { //內(nèi)部靜態(tài)資資源訪問映射 registry.addResourceHandler("/js/**").addResourceLocations("classpath:/static/js/"); registry.addResourceHandler("/css/**").addResourceLocations("classpath:/static/css/"); registry.addResourceHandler("/image/**").addResourceLocations("classpath:/static/image/"); //外部靜態(tài)資資源訪問映射 registry.addResourceHandler("/upload/**").addResourceLocations("file:D:/idea/java_workspace/image/upload/"); } /** * 添加攔截器鏈配置 */ @Override public void addInterceptors(InterceptorRegistry registry) { //注冊攔截器1,對商家管理系統(tǒng)進(jìn)行權(quán)限驗(yàn)證 InterceptorRegistration registration1 = registry.addInterceptor(new ShopAdminInterceptor()); //指定攔截器1要攔截的請求(支持*通配符) registration1.addPathPatterns("/shop_admin/**"); //注冊攔截器2,對超級管理員系統(tǒng)進(jìn)行權(quán)限驗(yàn)證 InterceptorRegistration registration2 = registry.addInterceptor(new SuperAdminInterceptor()); //指定攔截器2要攔截的請求(支持*通配符) registration2.addPathPatterns("/super_admin/**"); } /** * 添加無業(yè)務(wù)邏輯頁面跳轉(zhuǎn)配置 */ @Override public void addViewControllers(ViewControllerRegistry registry) { //首頁路由 registry.addViewController("/frontend/index").setViewName("frontend/index"); //店鋪列表路由 registry.addViewController("/frontend/to_shop_list").setViewName("frontend/shop_list"); //店鋪列表路由 registry.addViewController("/frontend/shop_detail").setViewName("frontend/shop_detail"); } }
到此這篇關(guān)于Springboot實(shí)現(xiàn)WebMvcConfigurer接口定制mvc配置詳解的文章就介紹到這了,更多相關(guān)WebMvcConfigurer接口配置內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
基于Mybatis plus 自動代碼生成器的實(shí)現(xiàn)代碼
本文通過實(shí)例代碼給大家介紹了基于Mybatis-plus 自動代碼生成器的相關(guān)知識,非常不錯(cuò),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2018-05-05解決idea不支持SpringBoot yml文件的圖文教程
這篇文章主要介紹了解決idea不支持SpringBoot yml文件,需要的朋友可以參考下2018-06-06SpringBoot前后端分離項(xiàng)目之打包、部署到服務(wù)器詳細(xì)圖文流程
作為后臺開發(fā),項(xiàng)目打包部署是經(jīng)常性的操作,下面這篇文章主要給大家介紹了關(guān)于SpringBoot前后端分離項(xiàng)目之打包、部署到服務(wù)器的相關(guān)資料,文中通過代碼示例介紹的非常詳細(xì),需要的朋友可以參考下2023-12-12解析SpringBoot @EnableAutoConfiguration的使用
這篇文章主要介紹了解析SpringBoot @EnableAutoConfiguration的使用,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-09-09Netty源碼解析NioEventLoop創(chuàng)建的構(gòu)造方法
這篇文章主要介紹了Netty源碼解析NioEventLoopGroup之NioEventLoop創(chuàng)建的構(gòu)造方法,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-03-03idea中安裝VisualVM監(jiān)控jvm的圖文教程
這篇文章主要介紹了idea中安裝VisualVM監(jiān)控jvm的教程,本文通過圖文并茂的形式給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-09-09Springboot如何實(shí)現(xiàn)代理服務(wù)器
這篇文章主要介紹了Springboot如何實(shí)現(xiàn)代理服務(wù)器問題,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-06-06