WebMvcConfigurer用法

WebMvcConfigurer 是 Spring MVC 框架中的一个重要接口,它定义了一系列回调方法,用于自定义基于 Java 的 Spring MVC 配置。当你使用 @EnableWebMvc 注解来启用 Spring MVC 时,可以通过实现 WebMvcConfigurer 接口来自定义默认的 MVC 配置。以下是该接口在使用过程中的一些常见用法及功能:

1. 配置拦截器

拦截器可以在请求处理的前后执行一些操作,例如身份验证、日志记录等。你可以通过实现 addInterceptors 方法来注册拦截器。

java 复制代码
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 注册自定义拦截器
        registry.addInterceptor(new MyInterceptor())
               .addPathPatterns("/**") // 拦截所有请求
               .excludePathPatterns("/login"); // 排除登录请求
    }
}

2. 配置静态资源映射

你可以通过实现 addResourceHandlers 方法来配置静态资源的映射,例如 CSS、JavaScript、图片等。

java 复制代码
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 映射静态资源路径
        registry.addResourceHandler("/static/**")
               .addResourceLocations("classpath:/static/");
    }
}

3. 配置跨域请求处理

跨域请求(CORS)允许浏览器在不同域名之间进行数据交互。你可以通过实现 addCorsMappings 方法来配置跨域请求的处理。

java 复制代码
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
               .allowedOrigins("*") // 允许所有域名进行跨域调用
               .allowedMethods("GET", "POST", "PUT", "DELETE") // 允许的请求方法
               .allowedHeaders("*") // 允许任何请求头
               .allowCredentials(true) // 允许携带凭证
               .maxAge(3600); // 预检请求的有效期,单位为秒
    }
}

4. 配置视图解析器

视图解析器用于将控制器返回的逻辑视图名解析为实际的视图对象。你可以通过实现 configureViewResolvers 方法来配置视图解析器。

java 复制代码
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setPrefix("/WEB-INF/views/");
        viewResolver.setSuffix(".jsp");
        registry.viewResolver(viewResolver);
    }
}

5. 配置消息转换器

消息转换器用于将请求中的数据转换为 Java 对象,以及将 Java 对象转换为响应数据。你可以通过实现 configureMessageConverters 方法来配置消息转换器。

java 复制代码
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.ArrayList;
import java.util.List;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);

        // 处理中文乱码问题
        List<MediaType> mediaTypes = new ArrayList<>();
        mediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
        converter.setSupportedMediaTypes(mediaTypes);

        converter.setFastJsonConfig(fastJsonConfig);
        converters.add(converter);
    }
}

总结

WebMvcConfigurer 接口提供了丰富的回调方法,允许你对 Spring MVC 的各个方面进行自定义配置。通过实现该接口,你可以灵活地定制 Spring MVC 应用的行为,满足不同的业务需求。

相关推荐
清晰-简洁2 小时前
Spring Boot 单元测试按需加载
spring boot·后端·单元测试
linuxxx1102 小时前
高考志愿填报辅助系统
redis·后端·python·mysql·ai·django·高考
MegatronKing3 小时前
Reqable 3.0版本云同步的实践过程
前端·后端·测试
快手技术3 小时前
闪耀NeurIPS 2025!快手13篇论文入选,Spotlight 成果跻身前三!
前端·后端
Starduster3 小时前
一次数据库权限小改动,如何拖垮半个互联网?——Cloudflare 2025-11-18 大故障复盘
数据库·后端·架构
一 乐3 小时前
宠物猫店管理|宠物店管理|基于Java+vue的宠物猫店管理管理系统(源码+数据库+文档)
java·前端·数据库·vue.js·后端·宠物管理
r***99823 小时前
在2023idea中如何创建SpringBoot
java·spring boot·后端
q***72193 小时前
Y20030018基于Java+Springboot+mysql+jsp+layui的家政服务系统的设计与实现 源代码 文档
android·前端·后端
i***39583 小时前
ShardingSphere-jdbc 5.5.0 + spring boot 基础配置 - 实战篇
java·spring boot·后端
AY呀3 小时前
DeepSeek:探索AI大模型与开发工具的全景指南
后端·机器学习