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的自動(dòng)配置可以滿足我們的大部分需求。但在保留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配置文件對(duì)Spring MVC進(jìn)行定制
*/
public interface WebMvcConfigurer {
//幫助配置HandlerMappings路徑匹配選項(xiàng),例如尾部斜杠匹配,后綴注冊(cè),路徑匹配器和路徑幫助器
default void configurePathMatch(PathMatchConfigurer configurer) {
}
//配置內(nèi)容協(xié)商選項(xiàng)
default void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
}
//配置異步請(qǐng)求處理選項(xiàng)
default void configureAsyncSupport(AsyncSupportConfigurer configurer) {
}
//通過轉(zhuǎn)發(fā)到Servlet容器的“默認(rèn)” Servlet,配置處理程序以委派未處理的請(qǐng)求
default void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
}
//除了默認(rèn)注冊(cè)的之外,還添加Converters和Formatters
default void addFormatters(FormatterRegistry registry) {
}
//添加Spring MVC生命周期攔截器,以對(duì)控制器方法調(diào)用和資源處理程序請(qǐng)求進(jìn)行預(yù)處理
default void addInterceptors(InterceptorRegistry registry) {
}
//添加處理程序以從Web應(yīng)用程序根目錄,類路徑等中的特定位置提供靜態(tài)資源,例如圖像,js和css文件
default void addResourceHandlers(ResourceHandlerRegistry registry) {
}
//配置跨源請(qǐng)求處理
default void addCorsMappings(CorsRegistry registry) {
}
//配置預(yù)先配置了響應(yīng)狀態(tài)代碼和/或用于呈現(xiàn)響應(yīng)主體的視圖的簡(jiǎn)單自動(dò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ū)懭胝?qǐng)求或響應(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配置,下面我會(huì)挑幾個(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í),就會(huì)自動(dòng)將/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”) 用于指定對(duì)外暴露的訪問路徑;
- addResourceLocations(“xxx”) 用于指定文件放置的目錄;
文件的放置目錄分兩種:項(xiàng)目?jī)?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) {
//注冊(cè)攔截器1,對(duì)商家管理系統(tǒng)進(jìn)行權(quán)限驗(yàn)證
InterceptorRegistration registration1 = registry.addInterceptor(new ShopAdminInterceptor());
//指定攔截器1要攔截的請(qǐng)求(支持*通配符)
registration1.addPathPatterns("/shop_admin/**");
//注冊(cè)攔截器2,對(duì)超級(jí)管理員系統(tǒng)進(jìn)行權(quán)限驗(yàn)證
InterceptorRegistration registration2 = registry.addInterceptor(new SuperAdminInterceptor());
/*指定攔截器2要攔截的請(qǐng)求(支持*通配符)*/
registration2.addPathPatterns("/super_admin/**");
//指定攔截器2不攔截的請(qǐng)求(支持*通配符)
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ái)系統(tǒng)
if(person != null && person.getUserId() > 0
&& person.getEnableStatus() == 1 && person.getPersonType() == 2){
//如果驗(yàn)證通過,則返回true,放行請(qǐng)求,即用戶接下來的操作可以正常執(zhí)行
return true;
}
//如果不滿足登陸驗(yàn)證,則跳轉(zhuǎn)到登陸頁(yè)面
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)入超級(jí)管理員后臺(tái)系統(tǒng)
if(person != null && person.getUserId() > 0
&& person.getEnableStatus() == 1 && person.getPersonType() == 3){
//如果驗(yàn)證通過,則返回true,放行請(qǐng)求,即用戶接下來的操作可以正常執(zhí)行
return true;
}
//如果不滿足登陸驗(yàn)證,則跳轉(zhuǎn)到登陸頁(yè)面
response.sendRedirect("/o2o/local/to_login");
return false;
}
}無業(yè)務(wù)邏輯頁(yè)面跳轉(zhuǎn) addViewControllers()
項(xiàng)目開發(fā)中,時(shí)常會(huì)涉及到無業(yè)務(wù)邏輯的頁(yè)面跳轉(zhuǎn); 這個(gè)頁(yè)面跳轉(zhuǎn)沒有涉及到任何的業(yè)務(wù)邏輯,只是單純的路由跳轉(zhuǎn)過程;但卻需要在Controller中編寫路由方法來完成,每一個(gè)頁(yè)面跳轉(zhuǎn)都需要定義一個(gè)路由方法,個(gè)人感覺是挺麻煩滴。
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/frontend")
public class FrontendController {
/**
* 首頁(yè)路由
*/
@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ù)邏輯的頁(yè)面跳轉(zhuǎn); 擺脫路由方法這個(gè)麻煩,當(dāng)然你習(xí)慣使用路由方法來實(shí)現(xiàn)無業(yè)務(wù)邏輯的頁(yè)面跳轉(zhuǎn)也是沒問題滴哦.
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.*;
@Configuration
public class SpringMvcConfiguration implements WebMvcConfigurer {
/**
* 添加無業(yè)務(wù)邏輯頁(yè)面跳轉(zhuǎn)配置
* @param registry
*/
@Override
public void addViewControllers(ViewControllerRegistry registry) {
//首頁(yè)路由
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) {
//注冊(cè)攔截器1,對(duì)商家管理系統(tǒng)進(jìn)行權(quán)限驗(yàn)證
InterceptorRegistration registration1 = registry.addInterceptor(new ShopAdminInterceptor());
//指定攔截器1要攔截的請(qǐng)求(支持*通配符)
registration1.addPathPatterns("/shop_admin/**");
//注冊(cè)攔截器2,對(duì)超級(jí)管理員系統(tǒng)進(jìn)行權(quán)限驗(yàn)證
InterceptorRegistration registration2 = registry.addInterceptor(new SuperAdminInterceptor());
//指定攔截器2要攔截的請(qǐng)求(支持*通配符)
registration2.addPathPatterns("/super_admin/**");
}
/**
* 添加無業(yè)務(wù)邏輯頁(yè)面跳轉(zhuǎn)配置
*/
@Override
public void addViewControllers(ViewControllerRegistry registry) {
//首頁(yè)路由
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)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Springboot?Shiro?anno不啟作用問題及解決
在Shiro配置中遇到靜態(tài)資源被攔截的問題,通過排除LinkedHashMap過濾次序和將過濾器手動(dòng)創(chuàng)建而不是注冊(cè)到容器中解決,同時(shí),確保JwtUtil類也不注冊(cè)到容器中,以避免請(qǐng)求報(bào)Not?authorized錯(cuò)誤2026-03-03
IntelliJ?IDEA中初始化Java類的常用快捷方法詳解
這篇文章主要為大家詳細(xì)介紹了IntelliJ?IDEA中初始化Java類并設(shè)置所有屬性的常用快捷方法,文中的示例代碼講解詳細(xì),需要的小伙伴可以參考下2026-02-02
Spring 實(shí)現(xiàn)給Bean屬性注入null值
這篇文章主要介紹了Spring 實(shí)現(xiàn)給Bean屬性注入null值的操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-08-08
SpringBoot?2.x和3.x的核心區(qū)別詳解(這些變化你必須知道)
Spring Boot 3與Spring Boot 2之間存在多個(gè)方面的顯著區(qū)別,這些區(qū)別主要體現(xiàn)在Java版本依賴、模塊化支持、Web框架、技術(shù)棧和依賴項(xiàng)更新、功能增強(qiáng)和改進(jìn)等方面,這篇文章主要介紹了SpringBoot?2.x和3.x核心區(qū)別的相關(guān)資料,需要的朋友可以參考下2026-02-02

