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

相关推荐
long31618 分钟前
构建者设计模式 Builder
java·后端·学习·设计模式
Noii.1 小时前
Spring Boot初级概念及自动配置原理
java·spring boot·后端
探索java1 小时前
Tomcat Server 组件原理
java·后端·tomcat
咕白m6251 小时前
通过 C# 高效提取 PDF 文本的完整指南
后端·c#
smallyu1 小时前
Go 语言 GMP 调度器的原理是什么
后端·go
掉头发的王富贵2 小时前
ShardingSphere-JDBC入门教程(上篇)
spring boot·后端·mysql
盖世英雄酱581362 小时前
必须掌握的【InheritableThreadLocal】
java·后端
LovelyAqaurius2 小时前
乐观锁及其实现方式详解
后端
绝无仅有2 小时前
编写 Go 项目的 Dockerfile 文件及生成 Docker 镜像
后端·面试·github
tager2 小时前
🍪 让你从此告别“Cookie去哪儿了?”
前端·javascript·后端