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 应用的行为,满足不同的业务需求。

相关推荐
Asthenia04122 分钟前
Spring声明式事务失效场景分析与总结
后端
Asthenia04128 分钟前
Spring七种声明式事务传播机制深度解析:内外层行为与异常处理
后端
努力的小雨35 分钟前
行业案例分享:汽车售后智能助手
后端
GoGeekBaird1 小时前
69天探索操作系统-第53天:高级分布式操作系统算法和共识协议
后端·操作系统
小杨4042 小时前
springboot框架项目实践应用八(validation自定义校验)
spring boot·后端·架构
Cloud_.2 小时前
Spring Boot整合Sa-Token极简指南
java·后端·springboot·登录校验
冬冬小圆帽3 小时前
防止手机验证码被刷:React + TypeScript 与 Node.js + Express 的全面防御策略
前端·后端·react.js·typescript
陈明勇3 小时前
chromem-go:Go 语言 RAG 应用的高效轻量级向量数据库
后端·go
掘金詹姆斯3 小时前
从Guava缓存源码提炼业务开发心法:Get方法暗藏的12个高并发设计哲学
后端