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 分钟前
InitializingBean详解与项目实战应用
后端
间彧2 分钟前
@PostConstruct详解与项目实战应用
后端
jiajixi6 分钟前
Go 异步编程
开发语言·后端·golang
QX_hao10 分钟前
【Go】--strings包
开发语言·后端·golang
秦禹辰28 分钟前
venv与conda:Python虚拟环境深度解析助力构建稳定高效的开发工作流
开发语言·后端·golang
seven97_top2 小时前
Springboot 常见面试题汇总
java·spring boot·后端
XXX-X-XXJ2 小时前
三、从 MinIO 存储到 OCR 提取,再到向量索引生成
人工智能·后端·python·ocr
该用户已不存在2 小时前
7个没听过但很好用的Mac工具
后端·开源
码事漫谈2 小时前
如何设置 Visual Studio 在调试停止时自动关闭控制台
后端